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>
相关推荐
计算机安禾1 分钟前
【c++面向对象编程】第21篇:运算符重载基础:语法、规则与不可重载的运算符
java·前端·c++
__log14 分钟前
Vue 3 核心技术深度解析:从“会用API“到“懂原理、能表达“
前端·javascript·vue.js
Asurplus22 分钟前
【VUE】16、使用 wangEditor 富文本编辑器
vue.js·图片上传·wangeditor·富文本编辑器
ZC跨境爬虫1 小时前
跟着 MDN 学 HTML day_52:(深入 XPathExpression 接口)
开发语言·前端·javascript·ui·html·音视频
不会写DN1 小时前
通过白名单解决 pnpm i 报错 Ignored build scripts
javascript·面试·npm
UXbot1 小时前
AI 原型工具零设计基础操作指南与功能解析(2026)
前端·ui·产品经理·原型模式·web app
yuzhiboyouye2 小时前
VO一般java后端怎么转换成前端想要的数据
java·前端·状态模式
一 乐2 小时前
学院教学工作量统计|基于java+ vue学院教学工作量统计管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·学院教学工作量统计系统
小脑斧1232 小时前
从范式重构到工程落地:OpenTiny NEXT 引领前端智能化新范式
前端·hermesagent·opentiny next