记录一下使用sortable给人员列表加拖动排序的问题
如果直接加上拖动功能表格就没办法选择复制文字,还容易误触这边想着是给表格加上开关
然后在网上找一些资料和案例整理一下,在按下按钮时候改变状态创建Sortable与摧毁
//开启或关闭排序
actionSort(){
if (this.isDragSort){
const that = this
that.varsortable && that.varsortable.destroy()
}else{
this.rowDrop()//创建sortable
}
this.isDragSort=!this.isDragSort
}
顺便加个样式
<style lang="scss">
.sortable-chosen td {
background-color: rgba(64, 158, 255, 0.57) !important;
}
</style>
已经可以实现拖动改变表格了,然后将用户列表的数组重新排一下
//行拖拽
rowDrop() {
const tbody = document.querySelector('.el-table__body-wrapper tbody')
const _this = this
_this.varsortable = Sortable.create(tbody, {
ghostClass: 'sortable-ghost', //拖拽样式
animation: 150, // 拖拽延时,效果更好看
onEnd({ newIndex, oldIndex }) {
console.log('newIndex',newIndex)
console.log('oldIndex',oldIndex)
if (newIndex!=oldIndex){
let sortdata=[]
const currRow = _this.userList.splice(oldIndex, 1)[0]
_this.userList.splice(newIndex, 0, currRow)
}
}
})
},
使用splice进行替换,table是绑定userList的userList变化表格的数据就会变,可是发现变化是错误的,拉第三条到第一位时候不尽人意的错位了,找了好久发现是没有给table设置row-key的原因,这个还是比较重要的
<el-table
v-loading="loading"
:data="userList"
border
row-key="uid"
@selection-change="handleSelectionChange"
>
设置完成row-key如果遇到
[Vue warn]: Error in callback for immediate watcher “data”:
“TypeError: Cannot read properties of null (reading ‘reduce’)”
这个问题的话可以看一下你data绑定的list默认值,如果是null就会报错将默认值设置为[]就可以了
这里分页后的序号,如果第二页也是按照1,2,3,4的话会冲突,所以需要计算一下order算法也就是
当前行 + (当前页 - 1) * 当前页总行数 + 1
最终
//行拖拽
rowDrop() {
const tbody = document.querySelector('.el-table__body-wrapper tbody')
const _this = this
_this.varsortable = Sortable.create(tbody, {
ghostClass: 'sortable-ghost', //拖拽样式
animation: 150, // 拖拽延时,效果更好看
onEnd({ newIndex, oldIndex }) {
if (newIndex!=oldIndex){
let sortdata=[]
const currRow = _this.userList.splice(oldIndex, 1)[0]
_this.userList.splice(newIndex, 0, currRow)
_this.userList.forEach((item, index) => {
sortdata.push({'id':item.uid,'order':( (index+1)+(_this.queryParams.pageIndex-1) * _this.queryParams.pageSize )})//计算分页出来的序号
})
console.log(sortdata)
_this.setUserOrder(sortdata)
}
}
})
},