vue实现表格拖拽教程
Vue 表格拖拽实现方法
安装依赖库
推荐使用 vuedraggable 或 sortablejs 实现拖拽功能。通过 npm 或 yarn 安装:
npm install vuedraggable
# 或
yarn add vuedraggable
基础表格拖拽实现
在 Vue 组件中引入 vuedraggable,绑定数据到表格:
<template>
<draggable v-model="tableData" tag="table" item-key="id">
<template #item="{ element }">
<tr>
<td>{{ element.id }}</td>
<td>{{ element.name }}</td>
</tr>
</template>
</draggable>
</template>
<script>
import draggable from 'vuedraggable'
export default {
components: { draggable },
data() {
return {
tableData: [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
]
}
}
}
</script>
进阶功能配置 添加拖拽手柄和动画效果:
<draggable
v-model="tableData"
handle=".handle"
animation="200"
>
<template #item="{ element }">
<tr>
<td><span class="handle">☰</span></td>
<td>{{ element.name }}</td>
</tr>
</template>
</draggable>
跨表格拖拽实现
设置 group 属性实现表格间拖拽:
<draggable
v-model="list1"
group="tables"
@end="onDragEnd"
>
<!-- 表格内容 -->
</draggable>
<draggable
v-model="list2"
group="tables"
>
<!-- 表格内容 -->
</draggable>
与 Element UI 集成 在 Element UI 表格中使用拖拽:
<el-table :data="tableData" row-key="id">
<el-table-column label="拖拽" width="80">
<template #default>
<i class="el-icon-rank" style="cursor: move"></i>
</template>
</el-table-column>
<!-- 其他列 -->
</el-table>
<script>
import Sortable from 'sortablejs'
export default {
mounted() {
this.rowDrop()
},
methods: {
rowDrop() {
const tbody = document.querySelector('.el-table__body-wrapper tbody')
Sortable.create(tbody, {
onEnd: ({ newIndex, oldIndex }) => {
const currRow = this.tableData.splice(oldIndex, 1)[0]
this.tableData.splice(newIndex, 0, currRow)
}
})
}
}
}
</script>
注意事项
- 确保为每行数据设置唯一的
key值 - 复杂场景建议使用
Sortable.js原生库 - 移动端需添加
touch事件支持 - 拖拽后及时更新后端数据
以上方法可根据实际需求组合使用,实现从简单到复杂的表格拖拽功能。







