开发遇到一个需求
客户不满意当前列表排序,想实现实施拖动改变顺序
用sortable.js 可以完美解决该问题
<el-table
:data="listData"
stripe
border
ref="tableList"
>
<el-table-column label="序号" prop="index" align="center" width="50"/>
<el-table-column prop="itemName" label="测试名称" align="center" show-overflow-tooltip/>
<el-table-column prop="itemCode" label="方法标准编号" align="center" show-overflow-tooltip/>
<el-table-column prop="detectResult" label="检验结果" align="center" show-overflow-tooltip/>
<el-table-column prop="subcontract" label="是否委外" align="center">
<template slot-scope="{row, $index}">
{{row.subcontract ? '是': '否'}}
</template>
</el-table-column>
</el-table>
import Sortable from 'sortablejs'
this.$nextTick(() => {
const el = this.$refs.tableList.$el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0]
new Sortable(el, {
animation: 150,
draggable: "tr",
handle: "tr",
dataIdAttr: 'detectItemFlag',
onStart: ({oldIndex}) => {
console.log('起始位置',oldIndex)
this.startIndex = oldIndex
},
onChange:(evt) => {
// 改变序列
// oldIndex > newIndex 表示移动了两个列
const { newIndex } = evt;
// 拖动时实时更新索引,每拖动一列都会更新索引
// 先交换数据
this.endIndex = newIndex
if ( this.startIndex !== this.endIndex) {
// 交换listData中两个数据的位置
[this.listData[this.startIndex], this.listData[this.endIndex]] = [this.listData[this.endIndex], this.listData[ this.startIndex]];
}
// 交换完数据 oldIndex 应该为 newIndex
this.startIndex = newIndex
},
onEnd: (evt) => {
// 结束拖动后更新索引值
this.listData.map((item, index) => {
item.index = index + 1;
});
}
})
})
最终效果: