首页 > 代码库 > Vue-router结合transition实现app前进后退动画切换效果

Vue-router结合transition实现app前进后退动画切换效果

首先配置路由并且修改路由配置

路由配置就不讲了

VueRouter.prototype.goBack = function () {  //重点,给VueRoute添加一个goBack方法,用于记录路由的前进后退状态 this.isBack = true 
  this.isBack = true
  window.history.go(-1)
}

 

监听路由变化

 

<template>
  <div>
    <transition :name="transitionName">   //动态绑定路由动画
    <router-view class="Router"></router-view>
    </transition>
</div>
</template>

<script>
export default {
  data() {
    return {
      transitionName: ‘slide-right‘  // 默认动态路由变化为slide-right
    }
  },
  watch: {
   ‘$route‘ (to, from) {
    let isBack = this.$router.isBack  //  监听路由变化时的状态为前进还是后退
      if(isBack) {
        this.transitionName = ‘slide-right‘
      } else {
             this.transitionName = ‘slide-left‘
     }
  this.$router.isBack = false
  }
  }
 }
</script>

<style>
.Router {
position: absolute;
width: 100%;
transition: all .8s ease;
top: 40px;
}

.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>

 

路由前进的时候按正常方法走就行了,后退的时候调用goBack方法就OK

Vue-router结合transition实现app前进后退动画切换效果