1、在项目目录下安装 sortablejs:
npm install sortablejs --save
2、在要实现表格拖拽的文件中引入 sortablejs:
import Sortable from ‘sortablejs’
3.应用

一定要在nextTick里面去做调用,否则有可能不生效
this.$nextTick(() => {
this.initSortTable();
});

按照id进行排序,必须在nextTick里面调用否则数据会发生错乱并且排序不生效

// 初始化拖拽表单
initSortTable() {
// 获取 el-table
const tableTag = this.refs["dragTable"].refs["dragTable"].refs["dragTable"].el;
// 获取 tbody 节点
const elTbody = tableTag.querySelectorAll(
“.el-table__body-wrapper > table > tbody”
)[0];
// 拖拽排序
this.sortable = Sortable.create(elTbody, {
delay: 0,
animation: 300, // 拖拽延时,效果更好看
onEnd: evt => {
// 监听拖动结束事件
// console.log(this); // this是当前vue上下文
// console.log(evt.oldIndex); // 当前行的被拖拽前的顺序
// console.log(evt.newIndex); // 当前行的被拖拽后的顺序
// 下面将拖拽后的顺序进行修改
const currRow = this.ruleForm.rows.splice(
evt.oldIndex,
1
)[0];
this.ruleForm.rows.splice(evt.newIndex, 0, currRow);
this.$nextTick(() => {
this.ruleForm.rows.forEach((item, index) => {
item.id = index + 1;
});
});
}
});
},
本文介绍了如何在Vue项目中安装Sortable.js库并实现在表格中的拖拽排序功能,强调了务必在Vue的nextTick回调中进行DOM操作以确保数据同步和正确排序。
1386

被折叠的 条评论
为什么被折叠?



