vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue中el-table表格的拖拽排序

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

作者:好 运.

本描述主要介绍el元素-ui表格拖拽排序功能的实现方法,通过安装sortable.js插件来实现拖拽排序功能,并详细介绍了实现步骤,包括安装插件、引入插件以及实现代码

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)
      }
    })
  }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文