效果图 上移 下移 首先想到的是 数组的相互替换嘛
<template> <div> <div class="box" v-for="(item,index) in arr" :key="index"> {{item.cnName}} <div class="upDownWrapper"> <span class="up" @click="upClick(index)" v-if="index !== 0">上移</span> <span class="down" @click="downClick(index)" v-if="index !== arr.length - 1">下移</span> </div> </div> </div> </template> export default { data() { return { arr: [ { cnName: "第一" }, { cnName: "第二" }, { cnName: "第三" }, { cnName: "第四" } ] }; } };
主要方法是
methods: { // 上移 upClick(index) { console.log('upClick',index); let newArr = this.swapItems(this.arr, index, index - 1) this.arr = newArr }, // 下移 downClick(index) { console.log('downClick',index); let newArr = this.swapItems(this.arr, index, index + 1) this.arr = newArr }, // 上下移动的核心 swapItems(arr, index1, index2) { arr[index1] = arr.splice(index2, 1, arr[index1])[0]; return arr; } }