首先我們需要安裝sortable.js這款插件
npm install sortablejs
然后我們在頁面中引入這個插件
import Sortable from "sortablejs";
表格加上row-key=“id”
<el-table :data="userlist" ref="singleTable" highlight-current-row border row-key="id" class="load_table"> <el-table-column prop="id" 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.userlist.splice(e.oldIndex, 1)[0]; this.userlist.splice(e.newIndex, 0, targetRow); console.log(this.userlist);
//這塊根據自己需求處理 let temp = []; this.userlist.map((m, i) => { temp.push({ id: m.id, seq: i, }); }); console.log(temp); }, }); },
原文地址 https://blog.csdn.net/qq_40236722/article/details/102699830