随手记:使用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('销毁拖拽')
    },

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

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

peachSoda7

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值