1.使用sortablejs插件
用于el-table列表拖动排序
import Sortable from 'sortablejs' // 拖拽插件
mounted() { this.rowDrop() },
swap(arr, from, to) {
// 在这方法中按需求修改排序规则即可
if (from < 0 || from >= arr.length || to < 0 || to >= arr.length) return
const temp = arr[from]
arr[from] = arr[to]
arr[to] = temp
return arr
},
rowDrop() {
const that = this
const tbody = document.querySelector('.el-table__body-wrapper tbody')
Sortable.create(tbody, {
animation: 100,
delay: 100,
handle: '.move',
onEnd ({ newIndex, oldIndex }) {
let tableData = that.tableData
that.tableData = []
tableData = that.swap(tableData, oldIndex, newIndex)
that.tableData = tableData
}
})
},
<el-table row-key="id" :data="tableData" border style="width: 100%">
<el-table-column prop="content" label="活动内容" align="center" />
<el-table-column label="操作" align="center">
<template v-slot="{ row }">
<div><el-icon class="move"><Sort /></el-icon></div>
</template>
</el-table-column>
</el-table>
踩过的坑:
that.tableData = []
因为重新渲染后,附加的拖拽事件丢失,所以需要置空来解决table只能拖拽一次的问题
row-key="id"
缺失会导致拖动后的位置不准确
class="move"
绑定触发拖动事件
2.使用sortablejs-vue3插件
用于普通标签、图标等拖动排序
import { Sortable } from 'sortablejs-vue3'
const options = {
ghostClass: 'ghost',
dragClass: 'drag'
},
const itemKey = Math.random()
const swap = (arr, from, to) = {
// 在这方法中按需求修改排序规则即可
if (from < 0 || from >= arr.length || to < 0 || to >= arr.length) return
const temp = arr[from]
if (from > to) { for (let i = from; i >= to; i--) { arr[i] = arr[i-1] } }
if (from < to) { for (let i = from; i <= to; i++) { arr[i] = arr[i+1] } }
arr[to] = temp
return arr
},
const tagChange = (e) = {
this.itemKey = Math.random()
this.list= this.swap(this.list, e.oldIndex, e.newIndex)
},
const removeUser = (index) = {
this.list.splice(index, 1)
},
<Sortable
:key="itemKey"
:list="list"
:options="options"
item-key="key"
tag="div"
@end="tagChange"
>
<template #item="{ element, index }">
<div class="item">
<el-tag closable @close="removeUser(index)">
<span>{{element.name}}</span>
</el-tag>
</div>
</template>
</Sortable>
代码仅供参考