Vue3 + sortablejs 实现表格排序

1,671 阅读1分钟

SortableJS 是一个用于创建可排序列表的 JavaScript 库。创建可拖放的列表,使用户能够轻松地重新排列项目或元素。

  1. 多列表支持:可以创建多个可排序列表,可以在这些列表之间拖放元素。
  2. 嵌套列表:支持嵌套列表,可以创建具有层次结构的可排序列表,能够创建树形结构或多级列表。

安装 sortablejs

npm install sortablejs

搭建基础 HTML 结构

<template>
  <section style="width: 100%">
    <el-table row-key="id" :data="tableData" stripe border style="width: 100%">
      <el-table-column
        v-for="(item, index) in colList"
        :key="index"
        :prop="dropCol[index]?.prop"
        :label="item.label"
        :width="item.width || width"
        :class-name="item.cName"
      />
    </el-table>
  </section>
</template>
<script setup>
import { ref, onMounted } from "vue";
import Sortable from "sortablejs";
import { _colList, _dropCol, _TableList } from "./data.js";

const dropCol = ref(_dropCol);
const colList = ref(_colList);
const tableData = ref(_TableList);

image.png

行拖拽

const rowDrop = () => {
  const tbody = document.querySelector(".el-table__body-wrapper tbody");
  const sorttable = Sortable.create(tbody, {
    animation: 180,
    onEnd({ newIndex, oldIndex }) {
      const currRow = tableData.value.splice(oldIndex, 1)[0];
      tableData.value.splice(newIndex, 0, currRow);
    },
  });
};

列拖拽

const columnDrop = () => {
  const tHeader = document.querySelector(".el-table__header-wrapper tr");
  Sortable.create(tHeader, {
    animation: 180,
    onEnd: (evt) => {
      const oldItem = dropCol.value[evt.oldIndex];
      dropCol.value.splice(evt.oldIndex, 1);
      dropCol.value.splice(evt.newIndex, 0, oldItem);
    },
  });
};

onMounted 调用

onMounted(() => {
  rowDrop();
  columnDrop();
});

Oct-27-2023 12-58-45.gif