一、下载第三方包
# 二选一
npm install vuedraggable
npm insall sortablejs
二、在页面中引入
// draggable 依赖于 Sortable,当npm install vuedraggable时其实就有了 sortablejs
import draggable from "vuedraggable";
import Sortable from "sortablejs";
三、在页面使用
/** row-key必须指定唯一,否则拖拽排序会出问题 */
<el-table :data="tableData" row-key="id">
<el-table-column prop="id" label="ID"> </el-table-column>
<el-table-column prop="name" label="姓名" width="180"> </el-table-column>
</el-table>
drag() {
/**el获取到tbody部分 */
const el = document.querySelectorAll(
".el-table__body-wrapper > table > tbody"
)[0];
Sortable.create(el, {
disabled: false, // 拖拽不可用? false 启用
ghostClass: 'sortable-ghost', //拖拽样式
animation: 150, // 拖拽延时,效果更好看
onEnd: (e) => { // 拖拽结束时的触发
let arr = this.tableData; // 获取表数据
arr.splice(e.newIndex, 0, arr.splice(e.oldIndex, 1)[0]); // 数据处理,获取最新的表格数据
this.$nextTick(function () {
this.tableData = arr;
console.log(this.tableData)
})
},
});
},
/** 在created中调用 */
created() {
this.$nextTick(() => {
this.drag();
});
},
//css 样式问题
<style lang="less" type="text/less">
.sortable-ghost {
opacity: 0.4;
background-color: #f4e2c9;
}
</style>
四、全部代码
<template>
<div class="home">
<!-- 一定要指定row-key 属性!,否则拖拽排序会出问题 -->
<el-table :data="tableData" row-key="id">
<el-table-column prop="id" label="ID"> </el-table-column>
<el-table-column prop="name" label="姓名" width="180"> </el-table-column>
</el-table>
</div>
</template>
<script>
// draggable 依赖于 Sortable,当npm install vuedraggable时其实就有了 sortablejs
import draggable from "vuedraggable";
import Sortable from "sortablejs";
export default {
name: "Home",
data() {
return {
tableData: [
{
name: "这是line1",
id: 1,
},
{
name: "这是line2",
id: 2,
},
{
name: "这是line3",
id: 3,
},
{
name: "这是line4",
id: 4,
},
],
};
},
created() {
this.$nextTick(() => {
this.drag();
});
},
methods: {
drag() {
const el = document.querySelectorAll(
".el-table__body-wrapper > table > tbody"
)[0];
console.log('el', document.querySelectorAll(
".el-table__body-wrapper > table > tbody"
)[0]);
Sortable.create(el, {
disabled: false, // 拖拽不可用? false 启用
ghostClass: 'sortable-ghost', //拖拽样式
animation: 150, // 拖拽延时,效果更好看
onEnd: (e) => { // 拖拽结束时的触发
let arr = this.tableData; // 获取表数据
arr.splice(e.newIndex, 0, arr.splice(e.oldIndex, 1)[0]); // 数据处理,获取最新的表格数据
this.$nextTick(function () {
this.tableData = arr;
console.log(this.tableData)
})
},
});
},
},
components: {
draggable,
},
};
</script>
<style lang="less" type="text/less">
.sortable-ghost {
opacity: 0.4;
background-color: #f4e2c9;
}
</style>