vuedraggable
不适合与 el-table
结合使用,所以选用 sortablejs
结合 el-table
实现拖拽表格行,几个关键的点:
- 需要给
el-table
添加row-key
属性,提供一个唯一的标识(否则会导致key复用,列表顺序与接口返回顺序不一致) - 获取到表格元素,使用
Sortable.create()
初始化后,可对其直接子元素进行拖拽 - 在
onEnd
事件获取拖拽后的数据,调用排序接口,再获取最新数据
xml
<template>
<div class="app-container">
<!-- row-key -->
<el-table class="el-drag-table" :data="tableData" row-key="id">
<el-table-column prop="name" label="Name"></el-table-column>
<el-table-column prop="age" label="age"></el-table-column>
<el-table-column label="操作">
<template #default>
<i class="el-icon-rank drag-handle" style="cursor: grab"></i>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script>
import Sortable from 'sortablejs'
import { deepClone } from '@/utils'
export default {
name: 'SortableTable',
data() {
return {
tableData: []
}
},
created() {
this.getList()
},
methods: {
// 模拟接口请求
getList() {
const time = new Date().toLocaleTimeString()
setTimeout(() => {
Promise.resolve().then(() => {
this.tableData = [
{ id: time, name: 'Matt', age: time },
{ id: time + 1, name: 'Matt', age: 2 },
{ id: time + 2, name: 'Matt', age: 3 }
]
this.initDragTable()
})
}, 200)
},
initDragTable() {
const tbody = document.querySelector('.el-table.el-drag-table .el-table__body-wrapper tbody')
Sortable.create(tbody, {
handle: '.drag-handle',
animation: 150,
onEnd: (evt) => {
// 获取排序后的数据
const { oldIndex, newIndex } = evt
const copyData = deepClone(this.tableData)
const movedRow = copyData[oldIndex]
copyData.splice(oldIndex, 1)
copyData.splice(newIndex, 0, movedRow)
console.log(deepClone(copyData))
// 调用排序接口...
// 调用列表接口,获取最新数据
this.getList()
}
})
}
}
}
</script>
<style scoped lang="scss"></style>
参考文档:
npm:www.npmjs.com/package/sor...
github:github.com/SortableJS/...