无子节点的表拖动排序#Vue3#Sortable插件
这里只需要保证row-key的值唯一就完事了,再利用Sortable插件获取到拖动的数据下标,然后调用接口对数据库的数据顺序修改。
<template>
<el-table :data="tableData" :row-key="getRowKey" style="width: 100%">
<el-table-column prop="date" label="Date" width="180" />
<el-table-column prop="name" label="Name" width="180" />
<el-table-column prop="address" label="Address" />
</el-table>
</template>
<script lang="ts" setup>
import Sortable from "sortablejs";
function getRowKey(row: any) {
return row.id;
}
// 拖动行排序
const changeRow = () => {
const el = document.querySelector(".el-table__body-wrapper tbody ") as any;
// const el = document.querySelector( ".el-table__body-wrapper > tbody > el-table__row el-table__row--level-0") as HTMLDivElement;
// :row-key="(record) => record.id"
Sortable.create(el, {
animation: 150, // 拖拽延时动画
ghostClass: "sortable-ghost", //拖拽样式
// draggable: ".el-table__row", //重点就是这里,指定拖拽的元素,把内容也算在行内
onEnd: (evt: any) => {
console.log("evt", evt);
const arr = menuList.value;
console.log("被交换数据", evt.newIndex);
console.log("当前数据", evt.oldIndex);
const preRow = menuList.value[evt.newIndex];
const curRow = menuList.value.splice(evt.oldIndex, 1)[0];
console.log("被交换数据", preRow);
console.log("当前数据", curRow);
arr.splice(evt.newIndex, 0, curRow);
for (let i = 0; i < menuList.value.length; i++) {
menuList.value[i].sort = i + 1;
}
console.log("menuList", menuList.value);
menuList.value.forEach((item: any) => {
item.pid = "";
// updateMenu修改菜单
updateMenu(JSON.parse(JSON.stringify(item))).then((res: any) => {
console.log(res.data);
});
});
// getList();
// nextTick(() => {
// menuList.value = arr;
// });
},
});
};
onMounted(()=>{
nextTick(()=>{
changeRow()
})
})
</script>