<div> <transition mode="out-in"> <button :key="isOn" @click="isOn = !isOn">{{ isOn ? 'On' : 'Off' }}</button> </transition> </div>
滑动过渡当元素设置为绝对定位,并互相覆盖,实现透明度过渡效果
<style> #demo{position:relative;} #demo button{position:absolute;left:40px;} .fade-enter,.fade-leave-to{opacity:0;} .fade-enter-active,.fade-leave-active{transition: 1s;} </style> <div> <transition > <button :key="isOn" @click="isOn = !isOn">{{ isOn ? 'On' : 'Off' }}</button> </transition> </div> <script> new Vue({ el: '#demo', data: { isOn: true }, }) </script>
下面是一个使用absolute和translate实现的类似滑动
<style> #demo{position:relative;} #demo button{position:absolute;left:40px;} .fade-enter,.fade-leave-to{opacity:0;} .fade-enter{transform:translateX(30px);} .fade-leave-to{transform:translateX(-30px);} .fade-enter-active,.fade-leave-active{transition: 1s;} </style>
如果设置in-out模式,将实现更酷的滑动效果
<style> #demo{position:relative;} #demo button{position:absolute;left:40px;} .fade-enter,.fade-leave-to{opacity:0;} .fade-enter{transform:translateX(30px);} .fade-leave-to{transform:translateX(-30px);} .fade-enter-active,.fade-leave-active{transition: 1s;} </style> <div> <transition mode="in-out"> <button :key="isOn" @click="isOn = !isOn">{{ isOn ? 'On' : 'Off' }}</button> </transition> </div> <script> new Vue({ el: '#demo', data: { isOn: true }, }) </script>
多组件过渡多个组件的过渡简单很多,不需要使用 key 特性。相反,只需要使用动态组件
下面是一个例子
<style> .fade-enter,.fade-leave-to{opacity:0;} .fade-enter-active,.fade-leave-active{transition: .5s;} </style> <div> <button @click="change">切换页面</button> <transition mode="out-in"> <component :is="currentView"></component> </transition> </div> <script> new Vue({ el: '#example', data:{ index:0, arr:[ {template:`<div>ComponentA</div>`}, {template:`<div>ComponentB</div>`}, {template:`<div>ComponentC</div>`} ], }, computed:{ currentView(){ return this.arr[this.index]; } }, methods:{ change(){ this.index = (++this.index)%3; } } })