<template>
    <div id="app">
      <transition :name="slideDirection">
        <router-view class="router-view"/>
      </transition>
    </div>
</template>

<script>
  export default {
    name: 'App',
    data() {
      return {
        slideDirection: 'slide-right', // 默认动态路由变化为slide-right
      }
    },
    watch: {
      /* eslint-disable */
      '$route'(to, from) {
        const toDepth = to.path.split('/').length
        const fromDepth = from.path.split('/').length
        this.transitionName = toDepth < fromDepth ? 'slide-right' : 'slide-left'

      },
    },
  }
</script>

<style lang="less">
  @import '~vux/src/styles/reset.less';
</style>
<style>
  #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    color: #666666;
    font-size: .28rem;
  }

  .router-view {
    position: absolute;
    width: 100%;
    transition: all .3s ease;
  }

  .slide-left-enter,
  .slide-right-leave-active {
    opacity: 0;
    -webkit-transform: translate(100%, 0);
    transform: translate(100%, 0);
  }

  .slide-left-leave-active,
  .slide-right-enter {
    opacity: 0;
    -webkit-transform: translate(-100%, 0);
    transform: translate(-100% 0);
  }
</style>

上面这种判断是前进还是后退的方法不是很完美, 还有一种方法直接通过在 vue-router 原型上加一个 goBack的方法, 然后在 goBack 里面去修改 view 的类名, 我试的时候没成功

VueRouter.prototype.goBack = function () { 
  this.isBack = true
  window.history.go(-1)
}
watch: {
   '$route' (to, from) {
    let isBack = this.$router.isBack  //  监听路由变化时的状态为前进还是后退
      if(isBack) {
        this.transitionName = 'slide-right'
      } else {
             this.transitionName = 'slide-left'
     }
  this.$router.isBack = false
  }
}



Logo

前往低代码交流专区

更多推荐