uniapp 实现拖动换位子的插件
时间: 2023-02-09 09:52:24 浏览: 1154
可以使用 v-draggable 插件来实现 uniapp 中的拖动换位功能。
首先,需要在项目中安装 v-draggable 插件:
```
npm install v-draggable
```
然后,在需要使用拖动换位功能的页面或组件中引入 v-draggable 插件:
```
import draggable from 'v-draggable'
export default {
mixins: [draggable],
// ...
}
```
接着,在模板中使用 v-draggable 指令即可实现拖动换位功能:
```
<template>
<view v-draggable="{ onMove: handleMove }">拖动我</view>
</template>
```
在 handleMove 方法中,可以处理拖动过程中的事件,如更新列表中的项目位置等。
完整示例代码如下:
```
<template>
<view class="list">
<view
v-for="(item, index) in list"
:key="index"
v-draggable="{ onMove: handleMove, onEnd: handleEnd }"
:data-index="index"
>
{{ item }}
</view>
</view>
</template>
<script>
import draggable from 'v-draggable'
export default {
mixins: [draggable],
data() {
return {
list: ['item1', 'item2', 'item3', 'item4']
}
},
methods: {
handleMove(event) {
const { clientX, clientY } = event.detail
const { top, left } = this.getElementTopLeft(event.currentTarget)
const x = clientX - left
const y = clientY - top
event.currentTarget.style.transform = `translate(${x}px, ${y}px)`
},
handleEnd(event) {
const { currentTarget } = event
const { index: fromIndex } = currentTarget.dataset
const toIndex = this.getElementIndex(currentTarget)
if (fromIndex !== toIndex) {
const [removed] = this.list.splice(fromIndex, 1)
this.list.splice(toIndex, 0, removed)
}
currentTarget.style.transform = ''
阅读全文