vue transition + keep-alive 实现过渡效果,和返回到上次浏览位置

先来看度过动画,和效果吧

 

 注意:在页面中慎用:position:absolute; 会导致无法返回到上次浏览位置

使用:include需要设置name属性

 

在需要缓存的页面添加如下代码,还有上面的name属性

  scrollY 在data里面定义 scrollY:0,这点我就偷个懒
  activated(){ //进入时读取位置 document.body.scrollTop = document.documentElement.scrollTop = this.scrollY console.log('进入时读取位置') }, deactivated(){ //离开时记录位置 this.scrollY = document.documentElement.scrollTop || document.body.scrollTop; console.log('离开时记录位置') },

 

在app.vue里面使用transition

<template>
  <div id="app">
    <transition :name="transitionName" mode="out-in">
        <keep-alive :include="cacheRoutes">
          <router-view></router-view>
        </keep-alive>
    </transition>
  </div>
</template>
<script>
export default {
  name: 'App',
  data () {
    return {
      cacheRoutes:'my_agent_more',
      transitionName: 'slide-left',
      state:true, //防止在500毫秒内同时出发两次
    }
  },
  // vue监听路由对象$route的方法
  watch: {
    // watch $route 决定使用哪种过渡
    $route (to, from) {
      if(this.state){
        // 根据传来的to.query.private 判断是需要左划还是右滑动
        const toDepth = to.query.private?true:false
        this.transitionName = toDepth?'slide-right': 'slide-left';
        this.state = false
      }
      // 500毫秒后重置
      setTimeout(()=>{
        this.state = true
      },500)
    }
  },
}
</script>
<style lang="less">
  .slide-left-enter,.slide-right-leave-active{
    transition: all .3s;
    opacity: 0;
    transform: translate(100vw,0);
  }
  .slide-left-leave-active,.slide-right-enter{
    transition: all .3s;
    opacity: 0;
    transform: translate(-100vw,0);
  }
</style>

 

posted @ 2020-03-09 09:22  龙卷风吹毁停车场  阅读(847)  评论(0编辑  收藏  举报