el-table 实现行拖拽排序,排序后更改背景色添加标记
使用插件:Sortablejs
安装插件
npm install sortablejs --save
引入插件
import Sortable from 'sortablejs';
使用方法根据el-tabla组件
<el-table
ref="tableNodeTop"
:data="tableData"
border
style="width: 100%"
row-key="id"
@selection-change="handleSelectionChange"
@row-click="handleClick"
highlight-current-row
>
切记必须使用row-key="id"必须添加,必须添加,必须添加不然会排序错乱
使用 ref=“tableNodeTop”
注意这里我是用了 handle: “.my-handle”, 默认拖拽时间鼠标右键不能复制文本,无法检索表单,不需要右键复制文本得可以不用,需要得表单里面这样写
**我这里只能拖拽序号列,其他列不能拖拽,但是可以右键复制本文 **
<el-table-column prop="order" label="序号">
<template slot-scope="scope">
<div :class="'my-handle'">
{{ scope.row.order }}
</div>
</template>
</el-table-column>
---------------------------------
<style lang="scss">
.my-handle {
cursor: move;
cursor: -webkit-grabbing;
}
</style>
mounted() {
this.pullSort(); //声明表格拖动排序方法
},
methods: {
//表格拖动排序方法
pullSort() {
// 通过ref获取Dom节点
const el = this.$refs.tableNode.$el.querySelectorAll(
".el-table__body-wrapper > table > tbody"
)[0];
this.sortable = new Sortable.create(el, {
handle: ".my-handle",//格式为简单css选择器的字符串,使列表单元中符合选择器的元素成为拖 动的手柄,只有按住拖动手柄才能使列表单元进行拖动
animation: 600, //拖拽动画(毫秒)
setData: function (dataTransfer) {
dataTransfer.setData("Text", "");
},
// 开始拖拽
onStart: (evt) => {
// 更改拖拽元素的背景色
evt.item.style.backgroundColor = "#cce8ff";
},
// 结束拖拽
onEnd: (evt) => {
const { oldIndex, newIndex } = evt;
// 创建一个新数组,这是为了确保原数组不被直接修改
const newDataArray = [...this.detaitableData];
// 使用splice方法移动元素到新位置
const movedItem = newDataArray.splice(oldIndex, 1)[0];
newDataArray.splice(newIndex, 0, movedItem);
// 更新组件的data
this.detaitableData = newDataArray;
// 打印更新后的数组
detailOrder(this.detaitableData).then((res) => {
if (res.status == "000000") {
this.getBoxTables();
this.$message.success("排序数据成功!");
} else {
this.$message.info(res.errors);
}
});
},
});
},
}