vue实现表格行拖动排序,表格使用vxe-table 配合sortablejs 实现
<template>
<div>
<vxe-table
border
ref="xTable1"
size="mini"
show-overflow
height="300px"
class="mytable-scrollbar"
:row-config="{ useKey: true }"
:scroll-y="{ enabled: false }"
:data="tableData"
>
<vxe-column field="name" title="Name">
<template #default="{ row }">
<span class="drag-btn">
<i class="el-icon-rank" style="font-size: 16px" />
</span>
<span>{{ row.name }}</span>
</template>
</vxe-column>
<vxe-column field="sex" title="Sex"></vxe-column>
<vxe-column field="age" title="Age"></vxe-column>
<vxe-column field="address" title="Address" show-overflow></vxe-column>
</vxe-table>
</div>
</template>
<script>
import Sortable from "sortablejs";
export default {
name: "Sortable",
data() {
return {
showHelpTip1: false,
tableData: [
{
id: 10001,
name: "Test1",
nickname: "T1",
role: "Develop",
sex: "Man",
age: 28,
address: "Shenzhen",
},
{
id: 10002,
name: "Test2",
nickname: "T2",
role: "Test",
sex: "Women",
age: 22,
address: "Guangzhou",
},
{
id: 10003,
name: "Test3",
nickname: "T3",
role: "PM",
sex: "Man",
age: 32,
address: "Shanghai",
},
{
id: 10004,
name: "Test4",
nickname: "T4",
role: "Designer",
sex: "Women",
age: 23,
address: "Shenzhen",
},
{
id: 10005,
name: "Test5",
nickname: "T5",
role: "Develop",
sex: "Women",
age: 30,
address: "Shanghai",
},
{
id: 10006,
name: "eee",
nickname: "T5",
role: "Develop",
sex: "Women",
age: 30,
address: "Shanghai",
},
{
id: 107,
name: "yuio",
nickname: "T5",
role: "Develop",
sex: "Women",
age: 30,
address: "Shanghai",
},
{
id: 185,
name: "qwe",
nickname: "T5",
role: "Develop",
sex: "Women",
age: 30,
address: "Shanghai",
},
{
id: 19,
name: "bnh",
nickname: "T5",
role: "Develop",
sex: "Women",
age: 30,
address: "Shanghai",
},
],
};
},
created() {
this.rowDrop();
},
methods: {
rowDrop() {
this.$nextTick(() => {
const xTable = this.$refs.xTable1;
this.sortable1 = Sortable.create(
xTable.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
{
animation: 200,
handle: ".drag-btn",
onEnd: ({ newIndex, oldIndex }) => {
const draggedRowId = this.tableData[oldIndex].id;
const replacedRowId = this.tableData[newIndex].id;
this.tableData.splice(
newIndex,
0,
this.tableData.splice(oldIndex, 1)[0]
);
let newArray = this.tableData.slice(0);
this.tableData = [];
this.$nextTick(function () {
this.tableData = newArray;
});
this.saveRowOrder(draggedRowId, replacedRowId);
this.$message.success("Sorting successful");
},
}
);
});
},
saveRowOrder(draggedRowId, replacedRowId) {
console.log("saveRowOrder", draggedRowId, replacedRowId);
},
},
};
</script>
<style lang="scss" scoped>
.mytable-scrollbar .drag-btn {
cursor: move;
font-size: 12px;
margin-right: 10px;
}
</style>