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书籍资料

猜你喜欢

转载自blog.csdn.net/qq_38128179/article/details/114276111