Realize the up and down movement of array elements in vue

Sometimes we need to realize the shifting position of the list elements up and down. We render the array data into the view, and the shifting up and down functions can be realized by swapping the positions of the array elements.

One, the list of arrays to be moved

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

Two, move up, move down function

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

Three, the effect

Four, attention

When the element is in the first position, it is prohibited to continue to move up, and when the element is in the last position, it is prohibited to continue to move down. We add the disabled attribute to the button, and index is the index in the for loop rendering view

    <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>

Articles are continuously updated every week. You can search for " Front-end Collection  " on WeChat to  read it for the first time, and reply to [ Video ] [ Book ] to receive 200G video materials and 30 PDF book materials

Guess you like

Origin blog.csdn.net/qq_38128179/article/details/114276111