<template>
<transition name="list" mode="out-in">
<keep-alive>
<component :is="currentView">
</component>
</keep-alive>
</transition>
</template>
<style scoped>
.list-item {
display: inline-block;
margin-right: 10px;
}
.list-enter-active, .list-leave-active {
transition: all 1s;
}
.list-enter, .list-leave-to
{
opacity: 0;
transform: translateY(30px);
}
</style>
当有相同标签名的元素切换时,需要通过 key 特性设置唯一的值来标记以让 Vue 区分它们
<transition :name="slide">
<keep-alive>
<component
:is="questionMap[currentQuestion.type]"
:key="index"
:currentQuestion="currentQuestion"
:index="index">
</component>
</keep-alive>
</transition>
给组件添加了key=”index”了之后,不管任何类型都有过渡效果了,因为
此时vue将每一个组件区分为不同的组件
问题2:先离开后另一个再进入。
同时生效的进入和离开的过渡不能满足所有要求,所以 Vue 提供了 过渡模式
in-out:新元素先进行过渡,完成之后当前元素过渡离开。
out-in:当前元素先进行过渡,完成之后新元素过渡进入。
因此我们需要在transition标签中添加mode来达成效果:
<transition :name="slide" mode="out-in">
<keep-alive>
<component
:is="questionMap[currentQuestion.type]"
:key="index"
:currentQuestion="currentQuestion"
:index="index">
</component>
</keep-alive>
</transition>
如果要使用列表排序的话,需要使用transition-group
<template>
<div id="list-demo" class="demo">
<button v-on:click="add">Add</button>
<button v-on:click="remove">Remove</button>
<transition-group name="list" tag="p">
<span v-for="item in items" v-bind:key="item" class="list-item">
{{ item }}
</span>
</transition-group>
</div>
</template>
<script>
new Vue({
el: '#list-demo',
data: {
items: [1,2,3,4,5,6,7,8,9],
nextNum: 10
},
methods: {
randomIndex: function () {
return Math.floor(Math.random() * this.items.length)
},
add: function () {
this.items.splice(this.randomIndex(), 0, this.nextNum++)
},
remove: function () {
this.items.splice(this.randomIndex(), 1)
},
}
})
</script>
<style>
.list-item {
display: inline-block;
margin-right: 10px;
}
.list-enter-active, .list-leave-active {
transition: all 1s;
}
.list-enter, .list-leave-to
/* .list-leave-active for below version 2.1.8 */ {
opacity: 0;
transform: translateY(30px);
}
</style>