Sortablejs+ElTable 拖拽
Sortablejs+ElTable 拖拽
element plus + sortablejs 实现表格拖拽功能
安装 sortablejs
1$ npm i sortablejs --save
在 Vue 中引入 sortablejs
1import Sortable from "sortablejs"
为拖拽的 table 配置 ref 和 row-key
1// row-key 设置为 table 数据源中能标识每一行唯一性的字段
2<el-table :data="datas" ref="dragTable" row-key="rowId">
3</el-table>
4const dragTable = ref();
创建拖拽表格实例
1const createDragTable = () => {
2 //引用的元素 通过 css 选择器 查到 table 元素
3 var table = dragTable.value.$el.querySelector('.el-table__body-wrapper tbody');
4 if(!table){
5 return;
6 }
7 //创建表格拖拽
8 var dTable = Sortable.create(table, {
9 animation:150,
10 onStart: () => {
11 //开始拖拽
12 },
13 onMove: (val) => {
14 /**
15 * 拖拽中
16 * val.dragged.rowIndex 正在拖拽行的下标
17 * val.related.rowIndex 预计拖拽后行的下标
18 */
19 //第一行不可拖到其他行,其他行也不可拖到第一行
20 if(val.dragged.rowIndex == 0 || val.related.rowIndex == 0){
21 return false;
22 }
23 },
24 onEnd: (el) => {
25 console.debug('结束拖拽',el.showIndex);
26 // 更新 table 的数据源
27 datas.splice(el.newIndex, 0, datas.splice(el.oldIndex, 1)[0]);
28 }
29 });
30}
在 onMounted 方法中调用
1onMounted(() => {
2 createDragTable();
3});