Vue---Vue+Element项目使用sortablejs插件实现表格拖拽排序

  • 安装sortablejs插件
npm install sortablejs --save
  • 页面引入sortablejs实现拖拽排序

       element table务必指定row-key,且row-key必须是一条数据的唯一标识,不然会出现排序不对的情况。但是row-key不可用index,因为拖拽后index会变,会有问题。

<template>
  <el-table border :data="tableData" row-key="uid">
    <el-table-column
      v-for="(item, index) in columns"
      :key="`col_${index}`"
      :prop="item.prop"
      :label="item.label"
    >
    </el-table-column>
  </el-table>
</template>
<script>
import Sortable from "sortablejs";              //引入sortablejs插件
export default {
  data() {
    return {
      columns: [
        { label: "日期", prop: "date" },
        { label: "姓名", prop: "name" },
        { label: "地址", prop: "address" },
      ],
      tableData: [
        {
          uid: "a7f1730112f7c62a55e51121234f7051",
          date: "2016-05-02",
          name: "王1",
          address: "100 弄",
        },
        {
          uid: "b1v3430112f7c62a55e51121234h6789",
          date: "2016-05-04",
          name: "王2",
          address: "200 弄",
        },
        {
          uid: "c45y630112f7c62a55e51121234mi90",
          date: "2016-05-01",
          name: "王3",
          address: "300 弄",
        },
        {
          uid: "dwe2330112f7c62a55e51121234kk890",
          date: "2016-05-03",
          name: "王4",
          address: "400 弄",
        },
      ],
    };
  },
  mounted() {
    this.rowDrop();                     // 行拖拽
    this.columnDrop();                  // 列拖拽
  },
  methods: {
    rowDrop() {                                     
      const tbody = document.querySelector(".el-table__body-wrapper tbody");
      const _this = this;
      Sortable.create(tbody, {
        draggable: ".el-table__row",
        onEnd({ newIndex, oldIndex }) {             //回调
          console.log(`原本位置:${_this.tableData[oldIndex].uid}`);
          console.log(`目标位置:${_this.tableData[newIndex].uid}`);
          const currRow = _this.tableData.splice(oldIndex, 1)[0];
          _this.tableData.splice(newIndex, 0, currRow);
        },
      });
    },
    columnDrop() {                                 
      const wrapperTr = document.querySelector(".el-table__header-wrapper tr");
      this.sortable = Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        onEnd: (evt) => {                           //回调
          const oldItem = this.columns[evt.oldIndex];
          this.columns.splice(evt.oldIndex, 1);
          this.columns.splice(evt.newIndex, 0, oldItem);
        },
      });
    },
  },
};
</script>

猜你喜欢

转载自blog.csdn.net/qq_39115469/article/details/106796834