Code前端首页关于Code前端联系我们

vue 应用:点击按钮,实现数据的上移和下移的玩法

terry 10个月前 (06-28) 阅读数 373 #Vue
文章标签 vue

介绍一个 vue 应用:点击按钮,实现数据的上移和下移的玩法。我们可以先看下效果图:

5985ae844458227e0ce6e710ee7ed420.png


废话不多说,代码搞起:

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

大家可以去试试吧。

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

评论列表

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门