Vue中el-table表格的拖拽排序

el-table实现拖拽

element-ui 表格没有拖拽排序的功能,只能使用sortable.js插件实现拖拽排序,当然也可以应用到其他的组件里面,用法类似,这里只说表格。

实现步骤:

1、安装sortable.js

npm install sortablejs --save

2、在需要的页面中引入

import Sortable from 'sortablejs'

3、实现表格拖动代码

mounted () {
    
    
   // 阻止默认行为
   document.body.ondrop = function (event) {
    
    
      event.preventDefault();
    event.stopPropagation();
  }
  // 调用 table拖拽排序
  this.rowDrop()
}

methods: {
    
    
  // 行拖拽
  rowDrop () {
    
    
    let tbody = document.querySelector('.el-table__body-wrapper tbody')
    let _this = this
    Sortable.create(tbody, {
    
    
      // or { name: "...", pull: [true, false, 'clone', array], put: [true, false, array] }
      group: {
    
    
        name: 'words',
        pull: true,
        put: true
      },
      animation: 150, // ms, number 单位:ms,定义排序动画的时间
      onAdd: function (evt) {
    
     // 拖拽时候添加有新的节点的时候发生该事件
        console.log('onAdd.foo:', [evt.item, evt.from])
      },
      onUpdate: function (evt) {
    
     // 拖拽更新节点位置发生该事件
        console.log('onUpdate.foo:', [evt.item, evt.from])
      },
      onRemove: function (evt) {
    
     // 删除拖拽节点的时候促发该事件
        console.log('onRemove.foo:', [evt.item, evt.from])
      },
      onStart: function (evt) {
    
     // 开始拖拽出发该函数
        console.log('onStart.foo:', [evt.item, evt.from])
      },
      onSort: function (evt) {
    
     // 发生排序发生该事件
        console.log('onUpdate.foo:', [evt.item, evt.from])
      },
      // 一般的业务就用onEnd结束拖拽就够了
      onEnd ({
     
      newIndex, oldIndex }) {
    
     // 结束拖拽
      	if(newIndex == oldIndex) return;
        let currRow = _this.tableData.splice(oldIndex, 1)[0]
        _this.tableData.splice(newIndex, 0, currRow)
      }
    })
  }
}

猜你喜欢

转载自blog.csdn.net/pink_cz/article/details/132640271
今日推荐