路由跳转记住滚动位置,返回时回到上次滚动位置

34 篇文章 0 订阅
21 篇文章 0 订阅

方法一: 利用Keep-Alive和监听器

1.首先在路由中引入需要的模块

{ 
path: ‘/home’, 
name: ‘home’, 
meta: { 
keepAlive: true // 需要缓存 
}, 
component: resolve => { require([‘../view/scrollDemo.vue’], resolve) } 
}

2.在App.vue中设置缓存组件

<keep-alive>   // 缓存组件跳转的页面
    <router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>  
  // 非缓存组件跳转页面
<router-view v-if="!$route.meta.keepAlive"></router-view>

3.在页面注册对应的事件

(1). 在data中定义一个初始值 scroll

(2). 在mouted中 ,mouted中的方法代表dom已经加载完毕

window.addEventListener('scroll', this.handleScroll);

(3).methods 用于存放页面函数

handleScroll () {
   this.scroll  = document.documentElement &&  document.documentElement.scrollTop
}

4、activated 为keep-alive加载时调用

activated() {
          if(this.scroll > 0){
            window.scrollTo(0, this.scroll);
            this.scroll = 0;
            window.addEventListener('scroll', this.handleScroll);
          }
    }

5.deactivated 页面退出时关闭事件 防止其他页面出现问题

deactivated(){
     window.removeEventListener('scroll', this.handleScroll);
    }

方法二:利用vuex + beforeRouteLeave + watch
main.js中:

var store = new Vuex.Store({
    state: {
        recruitScrollY: 0
    },
    getters: {
        recruitScrollY: state => state.recruitScrollY
    },
    mutations: {
        changeRecruitScrollY(state, recruitScrollY) {
            state.recruitScrollY = recruitScrollY;
        }
    },
    actions: {
    },
    modules: {}
})

组件中(/flashSaleListX为当前组件,即需要记住滚动条位置的组件):

methods:{
      isTabRoute: function() {
            if (this.$route.path === '/flashSaleListX') {
                  let recruitScrollY = this.$store.state.recruitScrollY
                  document.documentElement.scrollTop = recruitScrollY;
            }
      }
},
watch: {
             '$route': 'isTabRoute',
},
beforeRouteLeave(to, from, next) {
      let position = document.documentElement && document.documentElement.scrollTop; //记录离开页面时的位置
      if (position == null) position = 0
      this.$store.commit('changeRecruitScrollY', position) //离开路由时把位置存起来
      next()
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值