场景:用户要求做一个列表的排序,支持点击上下排序和拖拽排序。在此记录,以备不时之需。
效果展示:
排序前
排序后:
点击排序
点击排序没什么可说的 这里只提供思路和简略代码。
思路: 点击👆或👇排序 就是 把本层的sort(排序字段)、id(行数据唯一标识)和上一行的sort和id拿到一共四个数据,送到后端交叉储存就好了,这样就实现了点击排序很简单吧!!
代码:
上移排序:
updateOrderByUp(index, row) {//上移顺序
console.log("上移排序",index,row)
if (index == 0) {
this.$message.error('已经是第一个选项,无法上移!');
} else {
let data = {
id : row.id,
sort : index,
otherId : this.uploadArray[index - 1].id,
otherSort : index-1,
};
updateAttachOrderBy(data).then(res => {//数据库保存排序
//刷新列表数据
this.refreshAfterSort()
});
}
},
下移排序:
其他代码与除以下两行外并无其他差别
otherId : this.uploadArray[index + 1].id,
otherSort : index+1,
至于后端更简单,就是拿到id 然后把sort交换一下存库即可。
拖拽排序
我使用的是 sortable的插件 对表格数据进行拖拽排序
第一步 :导入插件库
npm install sortablejs --save
第一步 :引入插件
import Sortable from 'sortablejs'
第三步 :拖拽的核心代码
rowDrop() {
const tbody = document.querySelector(".el-table__body-wrapper tbody");
const _this = this;
Sortable.create(tbody, {
onEnd({ newIndex, oldIndex }) {
if (newIndex!==oldIndex){//有且仅在有效拖拽时执行方法
const currRow = _this.uploadArray.splice(oldIndex, 1)[0];
_this.uploadArray.splice(newIndex, 0, currRow);
_this.$set(value, "sort", index);
let dataList=[]
_this.uploadArray.forEach((value,index) => {
let data = {
id : value.id,
sort : index,
};
dataList.push(data)
})
//执行排序操作
updateAttachDragSort(dataList).then(res=>{
//拖拽后刷新列表数据
_this.refreshAfterSort()
})
}
},
});
},
this.$set用法详解:
this.$set
是Vue中的一个实例方法,用于在响应式对象上设置新的属性或修改已有的属性,并确保这些属性也是响应式的。它可以解决Vue响应式系统的一个限制,即无法检测到通过索引直接设置数组元素或通过Object.defineProperty添加的属性的变化。通过使用this.$set方法,可以显式地告诉Vue某个属性的值已经发生了变化,从而触发视图的更新
非常重要的一点 row-key="列表数据唯一标识"
此项为非常重要,不加此属性,拖拽排序会出错,拖拽完之后页面数据会非常奇怪!!非常重要。