vue对数组元素的上移下移和置顶等操作

1、要移动的数组列表

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

2、上移、下移、置顶函数

  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]));
    },
    // 补充置顶的操作
      arr.unshift(arr.splice(index , 1)[0]);
 
  },

3、页面代码

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

猜你喜欢

转载自blog.csdn.net/Selina_lxh/article/details/129008286