需求背景-支持拖动调整顺序
技术方案 sorttablejs
npm install sortablejs --save //安装
import Sortable from 'sortablejs' //使用的页面 引入
就是el-table上面必须要添加
row-key的值是在获取到的列表数据中必须具备唯一的值才不会导致拖拽顺序紊乱!!!!
row-key 可以取服务端下发唯一值 row-key=“id”,也可以使用一个函数返回 随机数如下
//随机数有个小问题 如果表格中有输入框
//key值设置成变化的值时会发生重绘,重绘会导致input失去焦点,把key设置成固定值
rowKey(){
return Math.random();
},
初始化获取表格数据
async get_List() {
this.listLoading = true
const { data } = await fetchList(this.listQuery)
this.tableData = data.items //获取 到表格数据
this.total = data.total
this.listLoading = false
this.oldList = this.tableData.map(v => v.id) // 旧的数据
this.newList = this.oldList.slice() //调整过的表格数据
this.$nextTick(() => {
this.set_row_sort()
})
},
行排序方法
set_row_sort() {
const el = this.$refs['ref-table'].$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0];
this.sortable = Sortable.create(el, {
ghostClass: 'sortable-ghost', // Class name for the drop placeholder, //整行拖拽
// handle: '.sortable-id', // 针对某一块实现拖动 在这行 column 添加对应的类名
setData: function(dataTransfer) {
// to avoid Firefox bug
// Detail see : https://github.com/RubaXa/Sortable/issues/1012
dataTransfer.setData('Text', '');
},
onEnd: evt => {
const targetRow = this.tableData.splice(evt.oldIndex, 1)[0];
this.tableData.splice(evt.newIndex, 0, targetRow);
console.log('tableData', this.tableData);
// for show the changes, you can delete in you code
const tempIndex = this.newList.splice(evt.oldIndex, 1)[0];
this.newList.splice(evt.newIndex, 0, tempIndex);
// this.$refs['ref-table'].doLayout(); //解决表格错乱
}
});
},
this.sortable.destroy(); // 销毁拖拽表格