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>
相关推荐
吃口巧乐兹12 小时前
异步异常处理:AggregateException 的拆解与最佳实践
javascript
柒和远方13 小时前
每日一学V017:用 Prompt 做 NLP:解构赋值与 AI 全栈的第一次实战
javascript·架构·代码规范
鹿青13 小时前
给设计稿做体检:我搓了个 Skill,专治 Figma 转代码出垃圾
前端·claude·视觉设计
刘海不能乱1613 小时前
Java JUC源码分析系列笔记-Synchronized
vue.js
陈_杨13 小时前
鸿蒙APP开发:足球战术App怎么做拖拽交互?球员拖动与路线绘制
前端
陈_杨13 小时前
鸿蒙APP开发:如果你想在鸿蒙App里做属性动画,@ohos.animator怎么用
前端
陈_杨13 小时前
鸿蒙APP开发:篮球App怎么画球场?鸿蒙Canvas绘图实战
前端
colofullove13 小时前
前端工程搭建与用户访问流程设计
前端
广州华水科技13 小时前
如何利用单北斗GNSS系统实现大坝的变形监测?
前端
砍材农夫13 小时前
物联网实战:Spring Boot MQTT | 模拟器Paho客户端拆解高性能
java·javascript·spring boot·后端·物联网·struts