可以用原生的dragstart、drag、dragend、dragover、drop、dragleave实现这个效果,但是有现成的轮子就不要重复造了,看效果:
<template><el-table :class="$options.name" :data="tableData" ref="table" row-key="ID"><!-- 注意:必须要定义row-key="ID",否者会导致拖拽顺序错乱 --><el-table-column type="index" label="序号" width="60" /><el-table-column prop="label" label="列名"><template slot-scope="scope"><el-link :type="scope.row.type" :underline="false">{{ scope.row.label }}</el-link></template></el-table-column></el-table>
</template>
<script>
import sortablejs from "sortablejs"; //npm install sortablejs --save
export default {name: "dragTableRow",data() {return {tableData: [{ ID: 1, value: 1, label: "显示文本1", type: `primary` },{ ID: 2, value: 2, label: "显示文本2", type: `success` },{ ID: 3, value: 3, label: "显示文本3", type: `warning` },{ ID: 4, value: 4, label: "显示文本4", type: `danger` },{ ID: 5, value: 5, label: "显示文本5", type: `info` },],};},mounted() {this.initDragSortTableRow(); //拖拽表格行排序},methods: {initDragSortTableRow() {let el = this.$refs.table.$el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0];sortablejs.create(el, {ghostClass: "ghostClass", //定义拖拽的时候接触到的行样式setData: (dataTransfer) => {dataTransfer.setData("自定义传参字段", "传输内容");},onEnd: (e) => {this.$g.array.moveArrayElement(this.tableData, e.oldIndex, e.newIndex); //修改数组的顺序console.log(e.originalEvent.dataTransfer.getData("自定义传参字段"));},});},},
};
</script><style lang="scss" scoped>
.dragTableRow {>>> .ghostClass {background-color: #ecf5ff;td {border-bottom-color: #409eff;}}
}
</style>