示例效果如下:
1):安装sortable.js插件
npm install sortablejs
2):示例代码
<template>
<div>
<el-table :data="tableDatas" ref="singleTable" highlight-current-row border row-key="id" class="load_table">
<el-table-column prop="id" width="80" label="序号" align="center"></el-table-column>
<el-table-column prop="name" width="120" label="姓名" align="center"></el-table-column>
</el-table>
</div>
</template>
<script>
import Sortable from 'sortablejs'
export default {
name: "",
data() {
return {
tableDatas: [
{
id:1,
name: '可可'
},{
id:2,
name: '排序'
},{
id:3,
name: '陈慕'
},{
id:4,
name: '于海峰'
},{
id:5,
name: '陈宇'
}
]
};
},
mounted() {
this.getDragSort();
},
methods: {
// 表格拖动排序
getDragSort() {
const el = this.$refs.singleTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
this.sortable = Sortable.create(el, {
ghostClass: 'sortable-ghost',
setData: function (dataTransfer) {
dataTransfer.setData('Text', '')
},
onEnd: e => {
// e.oldIndex为拖动一行原来的位置,e.newIndex为拖动后新的位置
const targetRow = this.tableDatas.splice(e.oldIndex, 1)[0];
this.tableDatas.splice(e.newIndex, 0, targetRow);
let selectLine = this.tableDatas[e.newIndex].id;//拖动行的id
let beforeId,afterId
// 拖动行的前一行
if( this.tableDatas[e.newIndex-1]){
beforeId = this.tableDatas[e.newIndex-1].id;
}else {
beforeId = ""
}
// 拖动行的后一行
if( this.tableDatas[e.newIndex+1]){
afterId = this.tableDatas[e.newIndex+1].id;
}else {
afterId = ""
}
this.postRequest({
url: "接口路径",
data: {
"selectLineId": selectLineId,
"beforeId": beforeId,
"afterId": afterId ,
},
success: (result) => {
if (result) {
this.$message({
message: "排序成功!",
type: "success",
})
}else {
this.$message({
message: "排序失败!",
type: "error"
});
}
}
})
}
})
},
}
};
</script>
<style lang = "less" scoped>
/deep/ .el-table tr:hover{
cursor: pointer;
}
</style>