<template>
<view class="">
<ul id="myList">
<li v-for="(item, index) in items" :key="item.id">
<span>{{ item.val }}</span>
<button @click="changeOrder(index)">上移</button>
<button @click="changeOrder(index, true)">下移</button>
</li>
</ul>
</view>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, val: 'A' },
{ id: 2, val: 'B' },
{ id: 3, val: 'C' },
{ id: 4, val: 'D' },
{ id: 5, val: 'E' }
]
}
},
methods: {
changeOrder(index, down = false) {
//判断是不是最后一项,如果是的话不进行下移
if (down) {
if (index === this.items.length - 1) {
return;
}
//下移
this.items.splice(index + 1, 0, this.items.splice(index, 1)[0]);
} else {
//判断是不是第一项,如果是就不进行上移
if (index === 0) {
return;
}
//上移
this.items.splice(index - 1, 0, this.items.splice(index, 1)[0]);
}
}
}
}
</script>