vue3 实现el-tabel 拖拽排序
时间: 2023-11-17 07:17:34 浏览: 97
要实现el-table的拖拽排序,可以使用Vue3的拖拽指令`v-drag`和`v-drop`。
首先,在table的列中添加一个拖拽的handle:
```html
<el-table-column label="排序" width="100">
<template #default="{ row }">
<span class="drag-handle" v-drag><i class="el-icon-sort"></i></span>
</template>
</el-table-column>
```
然后,给el-table添加`v-drop`指令,监听拖拽结束时的事件,并通过`splice`方法将拖拽的行插入到新的位置:
```html
<el-table v-drop="onDrop" :data="tableData" style="width: 100%">
<!-- ... -->
</el-table>
```
```js
import { ref } from 'vue';
export default {
setup() {
const tableData = ref([
// ...
]);
const onDrop = (event, dropData) => {
const dragData = JSON.parse(event.dataTransfer.getData('text'));
const fromIndex = dragData.index;
const toIndex = dropData.index;
// Remove the item from its old position
const [dragItem] = tableData.splice(fromIndex, 1);
// Insert the item into the new position
tableData.splice(toIndex, 0, dragItem);
};
return {
tableData,
onDrop,
};
},
};
```
最后,通过CSS样式让拖拽的handle可见,并且在拖拽过程中显示拖拽的行:
```css
.drag-handle {
cursor: move;
opacity: 0.5;
}
tr.is-dragging {
opacity: 0.6;
}
```
这样,就可以实现el-table的拖拽排序了。
阅读全文
相关推荐









