翼度科技»论坛 编程开发 JavaScript 查看内容

Vue如何实现数据的上移和下移

6

主题

6

帖子

18

积分

新手上路

Rank: 1

积分
18
Vue实现数据的上移和下移


场景

点击
  1. 上移
复制代码
  1. 下移
复制代码
按钮进行列表移动,
  1. 第一行
复制代码
  1. 不能上移
复制代码
  1. 最后一行
复制代码
  1. 不能下移
复制代码


解决方案
  1. <el-button @click="moveUp(index)">上移</el-button>
  2. <el-button @click="moveDown(index)">下移</el-button>

  3. data() {
  4.     return {
  5.         list: [
  6.             { id: 1, name: '张三' },
  7.             { id: 2, name: '李四' },
  8.             { id: 3, name: '王五' }
  9.         ]
  10.     }
  11. }

  12. // 上移
  13. moveUp (index) {
  14.     const arr = this.list
  15.     arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]))
  16. },
  17. // 下移
  18. moveDown (index) {
  19.     const arr = this.list
  20.     arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]))
  21. },
复制代码
禁用上下移逻辑


  • 禁用上移:
  1. :disabled="index === 0"
复制代码

  • 禁用下移:
  1. :disabled="index === list.length - 1"
复制代码
Vue表单批量上移 下移


效果图

  1.     // 上移
  2.     handDmoveUp () {
  3.       //选中行数据
  4.       let arrChecked = this.$refs.ref_ri_table.getCheckboxRecords();
  5.       //表格数据
  6.       let arr = this.tableData;
  7.         //正序遍历,保证移动完成的数据在下一次循环时位置不会再变动
  8.         a: for (let index1 = 0; index1 < arrChecked.length; index1++) {
  9.           b: for (let index2 = 0; index2 < arr.length; index2++) {
  10.             //选中数据定位到其在总数据中的位置时开始上移
  11.             if (arrChecked[index1] === arr[index2]) {
  12.               //选中数据与总数据索引相同时,说明已经上移到最上层,结束这层
  13.               //循环
  14.               if (index1 === index2) {
  15.                 break b;
  16.               }
  17.               //上移一位到达上一条数据的上方
  18.               arr.splice(index2 - 1, 0, arr[index2]);
  19.               //删除原数据
  20.               arr.splice(index2 + 1, 1);
  21.               //上移完成结束内存循环,开始移动下一条选中数据
  22.               break b;
  23.             }
  24.           }
  25.         }
  26. },


  27.   //下移
  28.     handMoveDown () {
  29.       let arrChecked = this.$refs.ref_ri_table.getCheckboxRecords();
  30.       let arr = this.tableData;
  31.       
  32.         a: for (let index1 = arrChecked.length - 1; index1 >= 0; index1--) {
  33.           b: for (let index2 = arr.length - 1; index2 >= 0; index2--) {
  34.             if (arrChecked[index1] === arr[index2]) {
  35.               //选中数据索引+表格数组长度-选中数组长度=选中数据索引,代表以及下移到最底部,结束下移
  36.               if (index1 + arr.length - arrChecked.length === index2) {
  37.                 break b;
  38.               }
  39.               arr.splice(index2 + 2, 0, arr[index2]);
  40.               arr.splice(index2, 1);
  41.               break b;
  42.             }
  43.           }
  44.         }
  45.         },
复制代码
总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

来源:https://www.jb51.net/javascript/3224045a0.htm
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具