vue3+elment plus + sortable 实现table表格可拖拽排序

时间:2025-01-19 16:18:40
<template> <div class="tableBox cmt-16"> <el-table :data="tableData" class="ELtable" :height="height" :width="width" stripe :header-cell-style="{ background: '#F3F3F4', color: '#323233' }" :row-key=" (row) => { return row.id; } " @selection-change="handleSelectionChange" > <el-table-column type="selection" width="30" :reserve-selection="true" class-name="selected"></el-table-column> <el-table-column label="序号" type="index" align="center" class-name="selected" width="100"></el-table-column> <el-table-column v-for="(column, index) in tableColumns" :key="`col_${index}_${mykey}`" :label="" :prop="" :index="index" :row-index="null" :sortable="true" :min-width=" ? : 100" class-name="allow-drag" ></el-table-column> </el-table> </div> </template> <script setup lang="ts"> import { ref, onMounted } from "vue"; import Sortable from "sortablejs"; /// 配置项中文文档 // 表格数据 const props = defineProps({ tableData: { type: [Array], defaule: [], }, tableColumns: { type: [Array], defaule: [], }, height: { type: [Number, String], default: "auto", }, width: { type: [Number, String], default: "100%", }, }); const emits = defineEmits<{ (event: "changeCol", data: Object): void; (event: "changeRow", data: Object): void; }>(); onMounted(() => { rowDrop(); columnDrop(); }); // 行拖拽 const rowDrop = () => { const tbody = document.querySelector(".ELtable tbody"); Sortable.create(tbody, { animation: 150, //动画参数 onEnd({ newIndex, oldIndex }) { // const currRow = (oldIndex, 1)[0] // (newIndex, 0, currRow) // 在此触发父组件中的方法 emits("changeRow", { oldIndex: oldIndex, newIndex: newIndex }); }, }); }; // 列拖拽 const columnDrop = () => { const tbody = document.querySelector(".ELtable tr"); Sortable.create(tbody, { animation: 180, delay: 10, filter: ".selected", // 过滤器,给不需要进行拖动的元素加上此类名,该元素不能主动拖动,但是其他的可拖动的依然可以与该元素交换位置 draggable: ".allow-drag", //允许拖拽的项目类名,没有该类名的元素主动被动都不能变换 onEnd: (evt) => { setTimeout(() => { emits("changeCol", { oldIndex: evt.oldIndex, newIndex: evt.newIndex }); }, 500); }, }); }; //复选框发生变化时触发 const multipleSelection = ref([]); const handleSelectionChange = (val) => { console.log(val, 666); }; </script> <style lang="scss" scoped> </style>