效果圖 上移 下移 首先想到的是 數(shù)組的相互替換嘛
<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函數(shù) 返回的是被刪除 項(xiàng)? 并且 會改變原數(shù)組
// arr.splice(index2, 1, arr[index])[0] 這個(gè)得到是的 被刪除的 項(xiàng) 并且原數(shù)組 已經(jīng)得到替換页衙。所以需要將被刪除項(xiàng) 設(shè)置為上一項(xiàng)的值
//如果解釋不是很清楚违霞。自己去控制臺 打印 玩玩? (主要是為自己理解做筆記)
? ? swapItems(arr, index1, index2) {
? ? ? arr[index1] = arr.splice(index2, 1, arr[index1])[0];
? ? ? return arr;
? ? }
? }
標(biāo)簽:?Vue,?JavaScript