前言
最近工作中遇到了一个表格拖拽排序的需求,我这里用了el-table结合SortableJS来实现。
一、安装插件
1.下载
代码如下(示例):
npm i sortablejs --save
或者
npm i sortablejs --save
二、使用
1.引入
import Sortable from 'sortablejs'//引入插件
2.html
<el-table
:data="tableData"
ref="table"
border
>
<el-table-column
label="序号"
type="index"
class-name="tableIndex"
align="center"
width="80"
>
</el-table-column>
<el-table-column prop="dataSetsName" align="center" label="数据集名称" min-width="280">
...
</el-table>
2.js
mounted() {
document.body.ondrop = function(event) {
// 阻止默认行为
event.preventDefault();
event.stopPropagation();
};
this.lineDrop(); //拖拽
},
methods:{
//拖拽方法
lineDrop() {
const tbody = document.querySelector(".el-table__body-wrapper tbody");
const _this = this;
Sortable.create(tbody, {
animation: 150, // ms, number 单位:ms,定义排序动画的时间
ghostClass: "ghostClass", //设置拖拽停靠样式类名
handle: ".tableIndex", // 格式为简单css选择器的字符串,使列表单元中符合选择器的元素成为拖动的手柄,只有按住拖动手柄才能使列表单元进行拖动
onEnd({ oldIndex, newIndex }) {//拖拽结束后方法
if (newIndex == oldIndex) return;//如果位置一样return
const tableArr = _this.tableData; // 表格数据
tableArr.splice(
newIndex,
0,
_this.tableData.splice(oldIndex, 1)[0]
);
_this.$nextTick(() => {
// 更新Vue组件的数据
_this.tableData = tableArr;
}
});
}
}
更多配置可以参考SortableJS文档
3.样式
我这里设置了拖拽行的停靠样式,给拖拽行的停靠时自定义了边框颜色;
css:
::v-deep {
// 停靠
.ghostClass > td {
&:first-of-type {
border-left: 1px solid $subject-color;
}
&:last-of-type {
border-right: 1px solid $subject-color;
}
border-top: 1px solid $subject-color;
border-bottom: 1px solid $subject-color;
}
}
4.问题
在实现过程中发现拖拽后数据已经发生变化,但是页面显示不正确,发现是和table 视图渲染有关;
拖拽前:
拖拽后:
解决方法:
给el-table 加上 “row-key”属性来优化 Table 的渲染即可。
<el-table
:data="tableData"
ref="table"
row-key="id"
border
></el-table>