vue ~~ 路由切换时 transition添加动画

第一步:

给路由router-view添加动画,必须name 和 key都设置,如果没有唯一值key,就会没有动画效果

<transition :name="transitionName">
      <router-view class="child-view"
                   :key="$route.name"></router-view>
</transition>

 

第二步:

在data里定义动画变量:transitionName

data () {
    return {
      transitionName: ''
    };
},

第三步:

监测路由变化,判断前进还是后退,进行不同的class赋值

  watch: {
    $route: {
      deep: true,
      immediate: true,
      handler (to, from) {
        if (from != undefined && to.meta.footerIndex > from.meta.footerIndex) {
          this.transitionName = 'slide-left';
        } else {
          this.transitionName = 'slide-right';
        }
      }
    },
},

第四步:

设置class

/* 动画效果 */
.child-view {
  position: absolute;
  width: 100%;
  transition: all 0.8s cubic-bezier(0.55, 0, 0.1, 1);
}
.slide-right-enter-active,
.slide-right-leave-active,
.slide-left-enter-active,
.slide-left-leave-active {
  will-change: transform;
  transition: all 500ms;
  position: absolute;
}

.slide-right-enter {
  opacity: 0;
  transform: translate3d(-100%, 0, 0);
}

.slide-right-leave-active {
  opacity: 0;
  transform: translate3d(100%, 0, 0);
}

.slide-left-enter {
  opacity: 0;
  transform: translate3d(100%, 0, 0);
}

.slide-left-leave-active {
  opacity: 0;
  transform: translate3d(-100%, 0, 0);
}

 

第五步: 

设置路由,需注意设置每个路由的独有的key,如我设置的就是footerIndex

       {
          path: '/', 
          name: 'index',
          meta: { footerIndex: 0 },
          component: index
        },
        {
          path: '/college',
          name: 'college',
          meta: {  footerIndex: 1 },
          component: college,
        },
        {
          path: '/collegeMajor/:attr/:type/:area',
          name: 'collegeMajor',
          meta: {footerIndex: 2 },
          component: college,
        },
        {
          path: '/major',
          name: 'major',
          meta: { footerIndex: 2 },
          component: major
        }

  

 

上一篇:[css] 怎么让英文单词的首字母大写?


下一篇:c++模板