Vue element表格实现拖动排序

时间:2023-03-15 15:58:03

最近在vue项目开发时,领导提了一个需求,需要实现*拖动element表格进行排序,小编上网查了很多方法,最终实现了这个功能。在这里小编跟大家分享一下如何实现这个功能的。

首先我们需要安装sortable.js这款插件

npm install sortablejs

然后我们在js中引入这个插件

import Sortable from "sortablejs";

表格加上row-key=“id”   我这里id是 stepsId

  <el-table :data="tableData" ref="singleTable" highlight-current-row border row-key="stepsId" class="load_table">
<el-table-column prop="stepsId" width="50" label="编号" align="center"></el-table-column>
<el-table-column prop="name" width="50" label="姓名" align="center" prop="index"></el-table-column>
</el-table>

实现排序方法如下所示:  

 mounted(){//页面挂在完成触发
this.dragSort();
},
//表格拖动排序
dragSort() {
const el = this.$refs.singleTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
this.sortable = Sortable.create(el, {
ghostClass: 'sortable-ghost',
setData: function (dataTransfer) {
dataTransfer.setData('Text', '')
},
onEnd: e => {
//e.oldIndex为拖动一行原来的位置,e.newIndex为拖动后新的位置
const targetRow = this.stepsList.splice(e.oldIndex, 1)[0];
this.stepsList.splice(e.newIndex, 0, targetRow);
var stepsIdArr = [];//重组合后的id循序
this.stepsList.forEach(x=>{
stepsIdArr.push(x.stepsId);
})
//更改排序号接口
updateSortNo({stepsIds:stepsIdArr}).then(res=>{
console.log("res.data",res.data);
})
}
})

},

this.singleTable: 对应表格的ref对象

this.sortable: 需要在data里定义

this.stepsList: table的表格list对象

 到这一步,我们已经实现页面*拖动表格的功能了 ,我的处理逻辑是排序后拿到新数组的id去接口按照新数组循序根据下标直接更改排序号。所以只传了排序好后的id就可以了

Vue element表格实现拖动排序