在做博客時监氢,想在導航切換時添加動畫效果。當前一個路由索引比要跳轉(zhuǎn)的路由索引小時管闷,向右滑動,反之向左滑動燥滑。代碼如下:
<template>
<transition :name="animateName">
<router-view class="view"></router-view>
</transition>
</template>
<script>
export default{
data(){
return{
animateName: 'slide-left',
pathList:['/home','/essays','/diary','/write','/about']
}
},
//監(jiān)聽路由的路徑渐北,可以通過不同的路徑選擇不同的切換效果
beforeRouteUpdate (to,from,next){
const prevPath = from.path;
const nextPath = to.path;
const prevIndex = this.pathList.findIndex(val=>prevPath === val);//前一個路由的索引
const nextIndex = this.pathList.findIndex(val=>nextPath === val);//當前點擊路由的索引
if(prevIndex > nextIndex){
this.animateName = 'slide-left';
}
else{
this.animateName = 'slide-right';
}
next();
}
}
</script>
<style>
/*路由跳轉(zhuǎn)動畫*/
.view {
transition: all .5s cubic-bezier(.55,0,.1,1);
}
.slide-left-enter, .slide-right-leave-active {
opacity: 0;
-webkit-transform: translate(50px, 0);
transform: translate(50px, 0);
}
.slide-left-leave-active, .slide-right-enter {
opacity: 0;
-webkit-transform: translate(-50px, 0);
transform: translate(-50px, 0);
}
<style>
總結(jié)
這里是通過v-router的鉤子函數(shù)進行的監(jiān)聽,也可以通過watch偵聽器進行監(jiān)聽铭拧,代碼如下:
watch:{
'$route' (to,from){
const prevPath = from.path;
const nextPath = to.path;
const prevIndex = this.pathList.findIndex(val=>prevPath === val);//前一個路由的索引
const nextIndex = this.pathList.findIndex(val=>nextPath === val);//當前點擊路由的索引
if(prevIndex > nextIndex){
this.animateName = 'slide-left';
}
else{
this.animateName = 'slide-right';
}
}
}