vue路由动画效果

在做博客时,想在导航切换时添加动画效果。当前一个路由索引比要跳转的路由索引小时,向右滑动,反之向左滑动。代码如下:

<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']
    }
  },
    //监听路由的路径,可以通过不同的路径选择不同的切换效果
    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>
/*路由跳转动画*/
  .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>

总结

这里是通过v-router的钩子函数进行的监听,也可以通过watch侦听器进行监听,代码如下:

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';
      }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容