vue中 el-table 实现拖拽排序教程(vue 中 element ui el-table基础上实现上下拖拽排序)
el-table基础上如何实现表格上下拖拽排序
element ui 表格没有自带的拖拽排序的功能,只能借助第三方插件Sortablejs来实现。
实现步骤:
1.安装Sortable.js
npm install sortablejs --save
2.在当前vue中JS代码中引入:
import Sortable from ‘sortablejs’
3.在当前vue文件template el-table中指定row-key,row-key必须是唯一的,如ID,不然会出现排序不对的情况。
注意:需要注意的是element table务必指定row-key,row-key必须是唯一的,如ID,不然会出现排序不对的情况。 row-key不可用index,因为拖拽后index会变,会有问题。
<el-table :data="tableData" row-key="id" border stripe>
.....
</el-table>
4.在当前vue文件JS中加下以下代码实现行上下拖拽或列拖拽
( 注意在mounted中挂载这两个方法)
<script>
import Sortable from 'sortablejs';
export default {
data () {
return {
tableData:[]
};
},
mounted () {
this.rowDrop();//行拖拽排序
this.columnDrop();//列拖拽排序
},
methods: {
// 行拖拽
rowDrop() {
// 此时找到的元素是要拖拽元素的父容器
const tbody = document.querySelector('.el-table__body-wrapper tbody');
const _this = this;
Sortable.create(tbody, {
// 指定父元素下可被拖拽的子元素
draggable: ".el-table__row",
onEnd({ newIndex, oldIndex }) {
const currRow = _this.tableData.splice(oldIndex, 1)[0];
_this.tableData.splice(newIndex, 0, currRow);
console.log('行拖拽end', 'newIndex:' + newIndex, 'oldIndex:' + oldIndex, 'currRow:', currRow)
//掉后台拖拽排序接口
_this._updateMoveData(newIndex, oldIndex, currRow)
}
});
},
//拖拽排序接口
async _updateMoveData(newIndex, oldIndex, currRow) {
//根据下标大小判断是向上还是向下拖了
if (newIndex > oldIndex) { //向下拖 下标减1
newIndex = newIndex - 1
} else if (newIndex < oldIndex) { //向上拖动 下标+1
newIndex = newIndex + 1
} else { //如果相等不拖动
return
}
var tableData = this.tableData
var beInsertIdData = tableData[newIndex]
console.log('beInsertIdData', beInsertIdData)
console.log('beInsertIdData.id ', beInsertIdData.id)
var beInsertId = beInsertIdData.id
var currRowId = currRow.id
console.log('beInsertId:', beInsertId, 'currRowId', currRowId)
var apiUrl = this.$_url._updateMoveDataDlUav
try {
let params = {
insertId: currRowId,
beInsertId: beInsertId
}
let res = await this.$post(this, apiUrl, params);
if (res.code == 10000) {
this.isdialog = false
this.loadList(false)
} else {
this.$message({ message: res.msg, type: 'warning' });
}
this.loading = false;
} catch (err) {
this.loading = false;
console.log('err', err);
// this.handleErr();
}
},
// 列拖拽
columnDrop () {
const wrapperTr = document.querySelector('.el-table__header-wrapper tr');
this.sortable = Sortable.create(wrapperTr, {
animation: 180,
delay: 0,
onEnd: evt => {
const oldItem = this.dropCol[evt.oldIndex];
this.dropCol.splice(evt.oldIndex, 1);
this.dropCol.splice(evt.newIndex, 0, oldItem);
//根据拿到的newIndex,oldIndex,currRow 掉后台的列排序接口....
}
});
}
}
};