const rowDrop = () => { let tbody: any = document.querySelector(".sortableArea .el-table__body-wrapper tbody"); sortable.value = Sortable.create(tbody, { group: { name: "table", pull: true, put: true }, handle: ".drag-icon", animation: 150, // ms, number 单位:ms,定义排序动画的时间 filter: ".noDrag", // 过滤.not-sort的元素 // 拖拽开始关闭同级子节点 onStart: function () { activeRows.value = JSON.parse(JSON.stringify(proTable.value.tableData)); }, onEnd(e: any) { console.log("onEnd", e); let oldRow = activeRows.value[e.oldIndex]; // 移动的那个元素 if (e.oldIndex === e.newIndex) return; const index = activeRows.value.indexOf(oldRow); if (index < 0) return; //删除拖动元素 activeRows.value.splice(e.oldIndex, 1); //挪到新位置 activeRows.value.splice(e.newIndex, 0, oldRow); //前置id let prefixRowId = null; if (e.newIndex - 1 < 0) { prefixRowId = 0; } else { prefixRowId = activeRows.value[e.newIndex - 1].id; } let params = { prefixRealmId: prefixRowId, id: oldRow.id }; realmSort(params); } }); };
onMounted(() => {
rowDrop();
});
总结:
handle: ".drag-icon",是只有点表格这个按钮才可以进行拖拽(关联了class)
<!-- 表格操作 --> <template #operation> <el-button link type="primary" class="popconfirm-btn drag-icon"> <i class="icon icon-list-view"></i> </el-button> </template>
在start里面进行深拷贝
在end里面,需要获取到当前id以及上级id
重要的点在于
//删除拖动元素 activeRows.value.splice(e.oldIndex, 1); //挪到新位置 activeRows.value.splice(e.newIndex, 0, oldRow);
要不取上级id会出现错乱,原因为,当前元素,从上(当前)往下(目标)和从下(当前)往上(目标)就会出现id的索引差一位的情况