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>
相关推荐
map_3d_vis1 小时前
百度地图 Hello World:5 分钟用 JSAPI 4.0 显示一张地图
前端·javascript·地图·百度地图
不要试图纠正别人1 小时前
构建 0 报错,产物体积翻倍:换引擎最容易漏的对账
前端·javascript
恋猫de小郭1 小时前
Android Keep Rules 解读,直接影响 Google Play 上架和曝光
android·前端·flutter
Hilaku2 小时前
面了 30 家公司拿到 2 个 Offer!
前端·javascript·程序员
延晗2 小时前
【从零开始 DeepSeek Harness 插件开发教程】三、从零开发 DeepSeek Harness 插件——完成第一个插件的挂载与运行
前端·人工智能
择势2 小时前
iOS 工程环境绝对隔离实践:开发机的"编不出"生产包
前端
某哈压力大2 小时前
Vue的双向绑定与自定义组件的v-model
前端·面试
CappuccinoRose2 小时前
前端开发交互体系 - 汇总篇
开发语言·前端·javascript·css·html·交互
天天鸭3 小时前
前端转全栈,要学会后端看项目的思维
前端·后端·ai编程
oil欧哟3 小时前
AI Agent 常用操作入门:独立目录、Plan 模式与跨话题交接指南
前端