<template>
  <div>
    <div>{{key}}</div>
    <div class="btn">
  <div @click="toTop()" class="item">至顶</div>
    <div @click="toUp()" class="item">上一级</div>
    <div @click="toDown()" class="item">下一级</div>
    <div @click="toBottom()" class="item">至底</div>
    </div>
    <div
      v-for="(item,key) in arr"
      class="item"
      :key="key"
      @click="getIndex(key)"
    >{{item}}</div>
  </div>
</template>

<script>
export default {
  name: "ArrChangeIndex",
  data() {
    return {
      arr: [1, 2, 3, 4, 5, 6, 7, 8, 9],
      key: -1
    };
  },
  methods: {
    getIndex(key) {
      console.log(key,'key')
      this.$set(this,'key',key)
    },
    //
    toTop() {
      if (this.key == -1 || this.key==0) return;
      //
      let item = this.arr.splice(this.key, 1)
      // 删除后的元素放到头部
      this.arr.unshift(...item)
      //
    },

    toUp() {
      if (this.key == -1 || this.key==0) return;

      // 拼接函数(索引位置, 要删除元素的数量, 元素)
      const delItems =  this.arr.splice(this.key, 1);
      this.arr.splice(this.key-1, 0, ...delItems )
      // console.log(this.key);
      this.$set(this,'key', this.key-1)
    },
    toDown() {
      // console.log(this.arr.length-1, 'length')
      if (this.key == -1 || this.key == this.arr.length-1) return;
       // console.log(this.key);
      const delItems =  this.arr.splice(this.key, 1);
      this.arr.splice(this.key+1, 0, ...delItems )
      this.$set(this,'key',this.key+1)
    },
    toBottom() {
      if (this.key == -1 || this.key == this.arr.length-1 ) return;
       // console.log(this.key);
      let item = this.arr.splice(this.key, 1)
      // 删除后的元素放到头部
      this.arr.push(...item)
      this.$set(this,'key',this.arr.length-1)
    },
  }
};
</script>

<style scoped>
.btn {
  display: flex;
}
.item {
  padding: 10px;
  cursor: pointer;
}
</style>