element ui table + sortablejs实现树形表格列拖拽

2,918 阅读1分钟

前言

element ui table + sortablejs实现树形表格列拖拽

需求

1、同级之间可进行拖拽,不同级别不允许拖拽
2、子类之间拖拽,只允许在同一父类下的子类之间可进行拖拽

HTML

          <el-table
            :data="tableData"
            class="drag"
            row-key="id"
            :tree-props="{ children: 'childProperties' }"
            style="width: 100%"
          >
            <el-table-column prop="name" label="属性"></el-table-column>
            ...
            ...
          </el-table>

JS

<script>
  import Sortable from 'sortablejs';
  export default {
    data() {
      return {
        tableData: [],
        copyTableData:[]
      };
    },
    mounted() {
      this.rowDrop();
    },
    methods: {
      //行拖拽
      rowDrop() {
        const tbody = document.querySelector('.drag .el-table__body-wrapper tbody');
        const _this = this;
        Sortable.create(tbody, {
          onEnd({ newIndex, oldIndex }) {
            let table = Object.assign([], _this.tableData);
            let newTable = [];
            // 将多维数据展开存为一维数据
            table.forEach((item) => {
                // 如果有子类,将子类也push进去
              if (item.childProperties && item.childProperties.length > 0) {
                newTable.push(item);
                item.childProperties.forEach((i) => {
                  i.parentId = item.identifier;
                  newTable.push(i);
                });
              } else {
                newTable.push(item);
              }
            });
            const sourceObj = newTable[oldIndex]; 
            const targetObj = newTable[newIndex];
            // 判断是否为一级
            if (!sourceObj.parentId && !targetObj.parentId) {
              // 操作数据为一级
              const currRow = newTable.splice(oldIndex, 1)[0];
              newTable.splice(newIndex, 0, currRow);
              let endTable = [];
              newTable.forEach((item) => {
                if (!item.parentId) {
                  endTable.push(item);
                }
              });
              _this.tableData = endTable;
              _this.copyTableData = endTable;
            } else {
              // 以下为其他不被允许的操作
              let oneResult = !sourceObj.parentId && targetObj.parentId;
              let TwoResult = sourceObj.parentId && !targetObj.parentId;
              let ThreeResult = sourceObj.parentId && targetObj.parentId && sourceObj.parentId !== targetObj.parentId;
              if (oneResult || TwoResult || ThreeResult) {
                _this.$message.warning('只能在同级之间进行拖拽排序');
                _this.$set(_this, 'tableData', []);
                // 重新渲染表格
                _this.$nextTick(() => {
                  _this.$set(_this, 'tableData', _this.copyTableData);
                });
              }
            }
          },
        });
      },
    },
  };
</script>