效果演示:
拖拽演示
先安装依赖
npm install sortable.js --save
页面引入
import Sortable from 'sortablejs'
完整代码如下:
<script setup lang="ts">
import { reactive, toRefs, onMounted} from 'vue'
import Sortable from 'sortablejs' // 安装引入此包 npm install sortable.js --save
// 声明数据
const state = reactive({
roleData: [
{ id: 1, name: 'zs', age: 18, address: '上海市普陀区泸定路' },
{ id: 2, name: 'ls', age: 28, address: '上海市浦东新区年家浜路' },
{ id: 3, name: 'ww', age: 38, address: '上海市杨浦区北京路' },
{ id: 4, name: 'll', age: 48, address: '上海市徐汇区人民广场' },
],
col: [
{ label: 'id', prop: 'id' },
{ label: '姓名', prop: 'name' },
{ label: '年龄', prop: 'age' },
{ label: '地址', prop: 'address' },
],
dropCol: [
{ label: 'id', prop: 'id' },
{ label: '姓名', prop: 'name' },
{ label: '年龄', prop: 'age' },
{ label: '地址', prop: 'address' },
],
tableKey: 1,
})
let { roleData, col, dropCol, } = toRefs(state)
// 拖动行
const rowDrop = () => {
const tbody: any = document.querySelector('.el-table__body-wrapper tbody')
Sortable.create(tbody, {
onEnd({ newIndex, oldIndex }: any) {
const currRow = roleData.value.splice(oldIndex, 1)[0]
roleData.value.splice(newIndex, 0, currRow)
console.log('新旧index',oldIndex, newIndex, currRow, roleData.value);
}
})
}
// 拖动列
const columnDrop = () => {
const wrapperTr: any = document.querySelector('.el-table__header-wrapper tr')
Sortable.create(wrapperTr, {
animation: 180,
delay: 0,
dragClass: "dragClass",
ghostClass: "ghostClass",
chosenClass: "chosenClass",
// 拖拽结束之后通过修改dropCol顺序改变表头顺序
onEnd: (evt: any) => {
if (evt.oldIndex === evt.newIndex) return
const oldItem = dropCol.value[evt.oldIndex - 1] // 备份当前拖拽的表头
dropCol.value.splice(evt.oldIndex - 1, 1) //把当前拖动的表头去掉 (-1 是因为第一列是序号)
dropCol.value.splice(evt.newIndex - 1, 0, oldItem) //把当前拖拽的表头添加到新位置 (-1 是因为第一列是序号)
}
})
}
// 在 onMounted钩子中调用
onMounted(() => {
// 阻止默认行为
document.body.ondrop = function (event) {
event.preventDefault();
event.stopPropagation();
};
rowDrop()
columnDrop()
})
</script>
<template>
<div class="sys-role-container">
<div class="draggable">
<el-table :data="roleData" style="width: 100%" element-loading-text="数据加载中" border fit row-key="id"
align="left">
<el-table-column type="index" label="序号" width="55" align="center" fixed />
<el-table-column v-for="(item, index) in col" :key="`col_${index}`" :prop="dropCol[index].prop"
:label="item.label" :show-overflow-tooltip="true">
</el-table-column>
</el-table>
</div>
</div>
</template>
<style lang='scss'>
// 拖拽
.dragClass {
background: rgba($color: #41c21a, $alpha: 0.5) !important;
}
// 停靠
.ghostClass {
background: rgba($color: #6cacf5, $alpha: 0.5) !important;
}
// 选择
.chosenClass:hover>td {
background: rgba($color: #f56c6c, $alpha: 0.5) !important;
}
</style>
没有及时记录,现在整理,好多细节都没提取,下次及时~
参考文档:element-ui table 表格组件实现可拖拽效果(行、列)_elementui table 行拖动-CSDN博客