目录
  • Vue实现数据的上移和下移
    • 场景
    • 解决方案
    • 禁用上下移逻辑
  • Vue表单批量上移 下移
    • 效果图
  • 总结

    Vue实现数据的上移和下移

    场景

    点击上移下移按钮进行列表移动,第一行不能上移最后一行不能下移

    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表单批量上移 下移

    效果图

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

    总结

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

    声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。