随手记:使用sortable.js 实现element-ui el-table 表格上下拖拽排序

需求场景:
表格可以实现上下拖拽row实现新排序

首先,安装sortable.js

npm install sortablejs --save

 引入表格排 

// 引入表格排序
import Sortable from 'sortablejs';

全局挂在组件

Vue.component('Sortable', Sortable)

使用页面引入

 import Sortable from 'sortablejs'

使用sortable.js表格一定要有唯一的row-key,一般绑定的是id,不然拖拽会不生效

data声明
sortableContainer: null,为的是后面如果有需要可以做销毁操作
 

因为我这里是表格组件,所以有些需要自己适当调整一下

      created(){
        this.getSortTableData();
      },

    // 更新表格
    getSortTableData() {
      this.$nextTick(()=>{
        setTimeout(() => {
          if(this.isSortTable) {
            let tableStyle =  document.querySelector(`#${this.tableId} .el-table`);
            tableStyle.style.cursor = 'pointer';
            this.rowDrop();
          }
        }, 500)
      })
    },

        // 行拖拽
    rowDrop() {
      console.log('行拖拽启动成功');
      // 拖拽必须给对应表格一个唯一的样式id值
      const tbody = document.querySelector(`#${this.tableId} .el-table__body-wrapper tbody`);
      console.log('tbody', tbody)
      const that = this;
      this.sortableContainer = Sortable.create(tbody, {
        forceFallback:true,
        animation: 150,
        dragClass: 'dragClass',
        chosenClass: 'chosenClass',
        ghostClass: "ghostClass",
        // 结束拖拽后的回调函数
        onEnd({ newIndex, oldIndex }) {
          console.log('拖动了行,序号(index)"'+ oldIndex + '"拖动到序号(index)"' + newIndex+'"');
          // 将oldIndex位置的数据删除并取出,oldIndex后面位置的数据会依次前移一位
          const currentRow = that.tableData.splice(oldIndex, 1)[0]; 
          console.log('currentRow', currentRow)
          // 将被删除元素插入到新位置(currRow表示上面的被删除数据)
          that.tableData.splice(newIndex, 0, currentRow); 
          console.log("拖动后的新数组:", that.tableData)
          // 拖拽结束后的回调函数
          let params = {
            // 拖动后的新序号
            newIndex,
            // 拖动了哪个序号
            oldIndex,
            // 当前行
            currentRow,
            // 拖动后的新数组
            tableData: that.tableData
          }
          that.$emit('sortableRowDrop', params);
        }
      })
    },

        // 销毁拖拽
    destroySortTableData() {
      this.sortableContainer.destroy();
      let tableStyle =  document.querySelector(`#${this.tableId} .el-table`);
      tableStyle.style.cursor = 'default';
      console.log('销毁拖拽')
    },

编辑文章实属不易,如有帮助请点赞收藏~

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-23 07:12:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-23 07:12:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-23 07:12:01       82 阅读
  4. Python语言-面向对象

    2024-02-23 07:12:01       91 阅读

热门阅读

  1. mysql 迁移-data目录拷贝方式

    2024-02-23 07:12:01       53 阅读
  2. Hexo + Github Action部署博客

    2024-02-23 07:12:01       54 阅读
  3. [ARC001B] リモコン

    2024-02-23 07:12:01       60 阅读
  4. 设计模式-工厂方法模式

    2024-02-23 07:12:01       43 阅读
  5. 一次学习引发我对于 synchronized 的再理解

    2024-02-23 07:12:01       45 阅读
  6. 设计模式--原型模式和建造者模式

    2024-02-23 07:12:01       49 阅读