效果圖 上移 下移 首先想到的是 數組的相互替換嘛

<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 }, // 上下移動的核心。splice函數 返回的是被刪除 項 並且 會改變原數組
// arr.splice(index2, 1, arr[index])[0] 這個得到是的 被刪除的 項 並且原數組 已經得到替換。所以需要將被刪除項 設置為上一項的值
//如果解釋不是很清楚。自己去控制台 打印 玩玩 (主要是為自己理解做筆記)
swapItems(arr, index1, index2) { arr[index1] = arr.splice(index2, 1, arr[index1])[0]; return arr; } }
