Vue + Element 表格实现拖拽排序

1,213 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第4天,点击查看活动详情 >>

安装sortablejs

npm install sortablejs --save

在需要的页面引入

import Sortable from 'sortablejs'

表格加上row-key="id"

<el-table ref="table" row-key="id" :data="tableData" style="width: 100%">
  <el-table-column prop="date" label="日期" width="180"></el-table-column>
  <el-table-column prop="name" label="姓名" width="180"></el-table-column>
</el-table>

数据

data() {
  return {
    tableData: [{ // 写的示例,项目中接口获取
      id:7458963256145,
      date: '2016-05-02',
      name: '王小虎',
      address: '上海市普陀区金沙江路 1518 弄'
    }, {
      id:1256358945623,
      date: '2016-05-04',
      name: '王小虎',
      address: '上海市普陀区金沙江路 1517 弄'
    }, {
      id:7485968563232,
      date: '2016-05-01',
      name: '王小虎',
      address: '上海市普陀区金沙江路 1519 弄'
    }, {
      id:4230568745963,
      date: '2016-05-03',
      name: '王小虎',
      address: '上海市普陀区金沙江路 1516 弄'
    }]
  }
}

表格排序

mounted () {
  // 调用 table拖拽排序 (有可能不生效,最好等表格数据获取后在调用,或加个this.$nextTick方法)
  this.rowDrop()
}

methods: {
    rowDrop() {
      const tbody = this.$refs.table.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      Sortable.create(tbody , {
      	animation: 300,
      	onEnd: e => {
	       	//e.oldIndex为拖动一行原来的位置,e.newIndex为拖动后新的位置
	        const targetRow = this.tableData.splice(e.oldIndex, 1)[0];
	        this.tableData.splice(e.newIndex, 0, targetRow);
	        let dragId = this.tableData[e.newIndex].id;//拖动行的id
	       	// 请求接口排序,后面具体需要什么参数,获取就行了,每个人需要不一样
	        
	   	 } 
      })
   }
}

方法介绍
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 ({ newIndex, oldIndex }) { // 结束拖拽
 	 let currRow = _this.tableData.splice(oldIndex, 1)[0]
 	 _this.tableData.splice(newIndex, 0, currRow)
}

注意点

1.如果你的onEnd方法不是箭头函数,如下面这样,需要在上面定义一下this指向,不然会报错

const _this = this
Sortable.create(tbody , {
	onEnd ({ oldIndex, newIndex }) {
	
	}
})