vue el-table实现拖拽排序

vue el-table实现拖拽排序

  • 安装
bash 复制代码
npm i sortablejs --save
  • 使用
html 复制代码
<template>
  <div>
      <!-- 列表 (支持拖拽排序) -->
        <el-table :data="pointList" ref="dragTableRef" row-key="id" style="width: 100%">
          <el-table-column width="60">
            <template #header>
              <i class="fa-solid fa-sort"></i>
            </template>
            <template #default>
              <i class="fa-solid fa-grip-vertical cursor-move"></i>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" min-width="140"></el-table-column>
          <el-table-column prop="code" label="编码" min-width="180"></el-table-column>
        </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import Sortable from 'sortablejs';

const dragTableRef = ref(null);

// 列表
const pointList = ref([
  {
    id: 1,
    name: '温度',
    code: 'TEMP-001',
  },
  {
    id: 2,
    name: '液压压力',
    code: 'PRESS-002',
  },
  {
    id: 3,
    name: '发电机振动',
    code: 'VIB-003',
  },
  {
    id: 4,
    name: '系统流量',
    code: 'FLOW-004',
  },
  {
    id: 5,
    name: '角度',
    code: 'ANGLE-005',
  },
]);

onMounted(() => {
   initSortable();
});


// 初始化拖拽排序
const initSortable = () => {
  const tableEl = dragTableRef.value?.$el || dragTableRef.value;
  if (!tableEl) {
    console.warn('表格DOM未找到');
    return;
  }

  const el = tableEl.querySelector('.el-table__body-wrapper tbody');
  if (!el) {
    console.warn('表格行容器未找到');
    return;
  }

  const sortable = new Sortable(el, {
    handle: '.fa-grip-vertical', // 拖拽图标的类名
    animation: 150,
    preventOnFilter: true,
    onEnd: ({ oldIndex, newIndex }) => {
      const currRow = pointList.value.splice(oldIndex, 1)[0];
      pointList.value.splice(newIndex, 0, currRow);
      console.log('排序完成,新顺序:', pointList.value);
    },
  });
};
</script>

<style scoped>
</style>
相关推荐
心.c3 小时前
大厂高频手写题
开发语言·前端·javascript
zhensherlock5 小时前
Protocol Launcher 系列:Working Copy 文件操作与高级命令详解
javascript·git·typescript·node.js·自动化·github·js
神の愛11 小时前
左连接查询数据 left join
java·服务器·前端
小码哥_常12 小时前
解锁Android嵌入式照片选择器,让你的App体验丝滑起飞
前端
郑寿昌13 小时前
IIoT本体迁移的领域扩展机制
服务器·前端·microsoft
深海鱼在掘金14 小时前
Next.js从入门到实战保姆级教程(第十一章):错误处理与加载状态
前端·typescript·next.js
深海鱼在掘金14 小时前
Next.js从入门到实战保姆级教程(第十二章):认证鉴权与中间件
前端·typescript·next.js
energy_DT14 小时前
2026年十五五油气田智能增产装备数字孪生,CIMPro孪大师赋能“流动增产工厂”三维可视化管控
前端
龙猫里的小梅啊14 小时前
CSS(四)CSS文本属性
前端·css
MXN_小南学前端14 小时前
watch详解:与computed 对比以及 Vue2 / Vue3 区别
前端·javascript·vue.js