vue-router的前进后退动画效果判定

vue中,我们常见的路由切换,有从A页面切换到B页面,然后从B页面后退回A页面,此时,如果没有做相应的处理,vue的页面切换动画就会是默认的一直是从右方进入。

对于我们用户来说,这就造成了视觉上面的不合理跳转。

这里分享一个小方法,大致流程如下:

首先,我们配置路由的meta,属性添加index(页面深度):

{
  path: '/aRouter',
  name: 'aRouter',
  component: () => import('@/pages/aRouter'),
  meta: {
    index: 1
  }
}

App.vue页面中,对路由包裹transaction标签,并且添加动态name属性:

 <transition :name="transitionName">
    <keep-alive include="xxx">
      <router-view class="router"></router-view>
    </keep-alive>
  </transition>

然后在App.vue的watch中监听我们设定好的路由index

watch: {
    $route(to, from) {
      if (from.meta.index <= to.meta.index) {
        this.transitionName = 'forward'
      } else {
        this.transitionName = 'back'
      }
    }
  }

这样,我们就可以通过设定的路由深度参数index来判定我们页面进入和进出动画到底是back还是forward