关于上移与下移

134 阅读1分钟

image.png

<template>
  <div>
    <el-card shadow="always">
      <h2>vue中实现数组元素的上移和下移</h2>

      <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>
    </el-card>
  </div>
</template>

<script>
import tan from "./tan.vue";
export default {
  name: "",
  components: { tan },
  created() {},
  mounted() {},

  data() {
    return {
      questionList: [
        { question: "第一个问题?" },
        { question: "第二个问题?" },
        { question: "第三个问题?" },
        { question: "第四个问题?" },
        { question: "第五个问题?" }
      ]
    };
  },
  computed: {},
  methods: {
    // 上移
    clickUp(index) {
      let arr = this.questionList;
      console.log(...arr.splice(index, 1, arr[index - 1]));
      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]));
    }
  }
};
</script>

<style lang="scss" scoped>
</style>


上移解释:

想把需要上移的那个的上一个覆盖掉自身 裁剪得到返回值就是自己本身 再次调用splice 把自己添加回来 覆盖掉原来的上一个的位置 下移同理

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // var fruits = ["Banana", "Orange", "Apple", "Mango"];
    // fruits.splice(2, 2);
    // console.log(fruits);// ['Banana', 'Orange']

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    // fruits.splice(0, 1,fruits[0]);
    // console.log(fruits);// ['Banana', 'Orange', 'Apple', 'Mango']  没变

    let a = fruits.splice(1, 1, fruits[0]); //上移
    console.log(fruits); // ['Banana', 'Banana', 'Apple', 'Mango']
    console.log("a", a); //['Orange']
    fruits.splice(0, 1, 'Orange')
    console.log(fruits); //['Orange', 'Banana', 'Apple', 'Mango']
  </script>

</body>

</html>