Element Plus 中的 el-table 实现拖拽排序功能

166 阅读1分钟
  1. 安装依赖
npm install sortablejs
  1. 引入
import Sortable from 'sortablejs';
  1. 在页面初始生命周期内使用
const el = document.querySelector('.sort-el-table .el-table__body-wrapper  table tbody'); 

if (el) {
    Sortable.create(el, {
        animation: 150,
        handle: '.drag-icon',  // 只有拖拽图标部分可以启动拖拽
        onEnd: async function (evt) { // 拖拽动作结束时触发
            let newIndex = evt.newIndex  // 排序后的索引位置
            let oldIndex = evt.oldIndex  // 排序前的索引位置

            if (newIndex !== oldIndex) {
                const updatedData = [...dataList];
                const [movedItem] = updatedData.splice(oldIndex, 1);
                updatedData.splice(newIndex, 0, movedItem);

                // 清空数据然后再重设数据以强制Vue重新渲染表格
                dataList= [];
                await nextTick();  // 确保Vue处理完数据清空

                updatedData.forEach((item, index) => {
                    item.sort = index; // 赋值为当前索引
                });

                dataList = updatedData; // 重新赋值以更新视图
            }
        }
    });
}