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

81 阅读1分钟

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

一、要移动的数组列表

  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>

如果移植到你的代码下运行,移动不起作用,可能是你页面中key值不唯一造成的,解决办法 :key="item.id" 设置成唯一的值。