文章目录
- 1. 实现效果
- 2. 安装 `sortablejs` 插件
- 3. 完整组件代码
- 4. 注意点
1. 实现效果
2. 安装 sortablejs
插件
sortablejs 更多用法
cnpm i --save sortablejs
3. 完整组件代码
<template><div class="home"><div class="body"><el-table :data="tableData" border row-key="date" class="draggable-table" style="width: 100%"><el-table-column prop="sortNo" label="序号"><template slot-scope="{ row }"><imgclass="handle":src="require('./icon-drop.png')"style="width: 20px; height: 20px; object-fit: contain"/></template></el-table-column><el-table-column prop="date" label="日期"></el-table-column><el-table-column prop="name" label="姓名"></el-table-column><el-table-column prop="address" label="地址"></el-table-column></el-table></div></div>
</template><script>import Sortable from 'sortablejs'export default {name: 'Demo',data() {return {tableData: [// 略去数据,与前段代码一直{ date: '2024-01-02', name: '张三1', address: '深圳市' },{ date: '2024-01-03', name: '李四2', address: '成都市' },{ date: '2024-01-04', name: '王五3', address: '重庆市' },{ date: '2024-01-05', name: '麻六4', address: '上海市' },{ date: '2024-01-07', name: 'kk5', address: '上海市01' },{ date: '2024-01-08', name: 'fantay6', address: '上海市02' },],}},mounted() {const tbody = document.querySelector('.draggable-table .el-table__body-wrapper tbody')new Sortable(tbody, {handle: '.handle', // handle's classanimation: 150,// 需要在odEnd方法中处理原始eltable数据,使原始数据与显示数据保持顺序一致onEnd: ({ newIndex, oldIndex }) => {const targetRow = this.tableData[oldIndex]this.tableData.splice(oldIndex, 1)this.tableData.splice(newIndex, 0, targetRow)console.table(this.tableData)},})},}
</script><style scoped lang="scss">.home {.body {width: 890px;height: 500px;border: #ff3366 solid 10px;box-sizing: border-box;padding: 20px;box-sizing: border-box;}}.handle {cursor: move;display: flex;align-content: center;}
</style>
4. 注意点
- 很多文章使用
Sortable.create
但是我这样用没生效,使用new Sortable
就行了 - 页面table添加类
draggable-table
handle
可以配置可拖拽的指定元素,默认是当前行触发