下图是我们页面展示内容,我们在实现按钮上的操作时再进行动画
下面是代码实现
<template>
<div>
<button @click="addNum">添加数字</button>
<button @click="removeNum">删除数字</button>
<button @click="shuffleNum">数字洗牌</button>
<transition-group name="list" tag="p">
<span v-for="(item,index) in num" :key="index" class="a">{{ item }}</span>
</transition-group>
</div>
</template>
<script>
import _ from 'lodash'
export default {
name: "VueList",
data() {
return {
num: [1, 2, 3, 4, 5, 6, 7, 8, 9],
numCounter: 9,
};
},
mounted() {},
methods: {
addNum() {
//this.num.push(this.numCounter++)
this.num.splice(this.randomNum(), 0, this.numCounter++);
},
removeNum() {
this.num.splice(this.randomNum(), 1);
},
shuffleNum(){
this.num = _.shuffle(this.num)
},
randomNum() {
return Math.floor(Math.random() * this.num.length);
},
},
};
</script>
<style scoped>
.a {
display: inline-block;
margin-right: 10px;
}
.list-enter-active,
.list-leave-active {
transition: all 1s ease;
}
.list-enter-from,
.list-leave-to {
opacity: 0;
transform: translateY(30px);
}
.list-leave-active{
position: absolute;
}
.list-move{
transition: transform 1s ease;
}
</style>
根据上面代码实现我们发现在数字的删除和添加是可以正常随机添加删除,但是无论添加删除的是哪个数字,动画都作用在最后一个元素数字上面。
这里将key绑定的值修改为item,即可正常添加动画
这里我们查看官方文档,发现当列表数据改变时,它根据key值是否有变化来决定是否修改原来的值还是做复用,我们使用index绑定key,会发现每次添加或删除数据的时候,前面的:key都没有改变,只有最后一个元素的key即绑定的index变化了,所以每次动画都作用在最后一个元素上面。
所以这里我们不推荐使用index绑定key。