vue+element实现表格的拖拽,并实现可手动关闭拖拽!
1.下载sortable.js:
npm install sortablejs --save
2.在当前页引入:
import Sortable from ‘sortablejs’
3.使用方法:
mounted() {
//使每次都可以拖拽
this.$nextTick(()=>{
setTimeout(()=>{
this.rowDrop();
},100)
})
},
// 行拖拽
rowDrop () {
const tbody = document.querySelector('.el-table__body-wrapper tbody')
Sortable.create(tbody, {
onEnd: ({ newIndex, oldIndex }) => {
const currRow = this.tableData.splice(oldIndex, 1)[0]
this.tableData.splice(newIndex, 0, currRow)
}
})
},
然后在需要拖拽的table表的属性加入<el-table style="width:100%" :data="pageData" border size="mini" v-loading="loading" row-key="id">
加入row-key="id"即可实现表格的拖拽
多说一句:我目前的项目需要做到如下效果
当用户点击开启调整才能让他去调整顺序,关闭则不可以,在网上看了很多资料后,如下操作可解决问题,
this.tableObject = Sortable.create(tbody, {
onEnd: ({ newIndex, oldIndex }) => {
const currRow = this.tableData.splice(oldIndex, 1)[0]
this.tableData.splice(newIndex, 0, currRow)
}
})
先将可拖拽放入一个对象中(我这里命名为tableObject),当用户点击关闭调整后,使用
this.tableObject.destroy()
来销毁这个对象即可!
如有错误,请大家多多指教!