当前位置: 代码网 > it编程>前端脚本>Vue.js > Vue如何实现数据的上移和下移

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

2024年06月10日 Vue.js 我要评论
vue实现数据的上移和下移场景点击上移或下移按钮进行列表移动,第一行则不能上移,最后一行则不能下移解决方案<el-button @click="moveup(index)">上移</

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;
            }
          }
        }
        },

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com