vue中实现数组元素的上移和下移

有时候我们需要实现列表元素上移和下移交换位置,我们把数组数据渲染到视图中,可以通过数组元素交换位置来实现上移和下移功能

一、要移动的数组列表

  data() {
    return {
      questionList: [
        { question: "第一个问题?" },
        { question: "第二个问题?" },
        { question: "第三个问题?" },
        { question: "第四个问题?" },
        { question: "第五个问题?" },
      ],
    };
  },

二、上移、下移函数

  methods: {
    // 上移
    clickUp(index) {
      let arr = this.questionList;
      arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]));
    },
    // 下移
    clickDown(index) {
      let arr = this.questionList;
      arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
    },
  },

三、效果

四、注意

当元素处于第一个位置时,禁止让它继续上移,当元素处于最后一个位置时,禁止让它继续下移。我们给按钮增加disabled属性,index为for循环渲染视图中的index

    <div v-for="(item, index) in questionList" :key="index">
      <p>{{item.question}}</p>
      <div class="btns">
        <!-- 上移 -->
        <Button :disabled="index == 0" @click="clickUp(index)"></Button>
        <!-- 下移 -->
        <Button :disabled="index == questionList.length - 1" @click="clickDown(index)"></Button>
      </div>
    </div>

文章每周持续更新,可以微信搜索「 前端大集锦 」第一时间阅读,回复【视频】【书籍】领取200G视频资料和30本PDF书籍资料

  • 17
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@Demi

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值