1. 程式人生 > >vue + vue-router 前進後退推拉動畫效果

vue + vue-router 前進後退推拉動畫效果

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