vue实现数据的上移和下移
场景
点击上移或下移按钮进行列表移动,第一行则不能上移,最后一行则不能下移

解决方案
<el-button @click="moveup(index)">上移</el-button>
<el-button @click="movedown(index)">下移</el-button>
data() {
return {
list: [
{ id: 1, name: '张三' },
{ id: 2, name: '李四' },
{ id: 3, name: '王五' }
]
}
}
// 上移
moveup (index) {
const arr = this.list
arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]))
},
// 下移
movedown (index) {
const arr = this.list
arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]))
},
禁用上下移逻辑
- 禁用上移:
:disabled="index === 0"
- 禁用下移:
:disabled="index === list.length - 1"
vue表单批量上移 下移
效果图

// 上移
handdmoveup () {
//选中行数据
let arrchecked = this.$refs.ref_ri_table.getcheckboxrecords();
//表格数据
let arr = this.tabledata;
//正序遍历,保证移动完成的数据在下一次循环时位置不会再变动
a: for (let index1 = 0; index1 < arrchecked.length; index1++) {
b: for (let index2 = 0; index2 < arr.length; index2++) {
//选中数据定位到其在总数据中的位置时开始上移
if (arrchecked[index1] === arr[index2]) {
//选中数据与总数据索引相同时,说明已经上移到最上层,结束这层
//循环
if (index1 === index2) {
break b;
}
//上移一位到达上一条数据的上方
arr.splice(index2 - 1, 0, arr[index2]);
//删除原数据
arr.splice(index2 + 1, 1);
//上移完成结束内存循环,开始移动下一条选中数据
break b;
}
}
}
},
//下移
handmovedown () {
let arrchecked = this.$refs.ref_ri_table.getcheckboxrecords();
let arr = this.tabledata;
a: for (let index1 = arrchecked.length - 1; index1 >= 0; index1--) {
b: for (let index2 = arr.length - 1; index2 >= 0; index2--) {
if (arrchecked[index1] === arr[index2]) {
//选中数据索引+表格数组长度-选中数组长度=选中数据索引,代表以及下移到最底部,结束下移
if (index1 + arr.length - arrchecked.length === index2) {
break b;
}
arr.splice(index2 + 2, 0, arr[index2]);
arr.splice(index2, 1);
break b;
}
}
}
},
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论