vue缓存页面返回到指定滚动位置

vue 中注册滚动事件与dom 并无不同

以下配合keep-alive 组件使用

在 mounted 注册滚动事件 

this.handleScroll 获取scrollTop
mounted(){
  window.addEventListener('scroll', this.handleScroll);
}

  

handleScroll () {
  let scrollTop = document.body.scrollTop;
  this.scroll = scrollTop;
}

keep-alive 组件激活时调用。该钩子在服务器端渲染期间不被调用。

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

keep-alive 组件停用时调用。该钩子在服务器端渲染期间不被调用。

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

 参考地址:  VUE

posted on 2018-01-29 15:30  LCFLY  阅读(8960)  评论(0编辑  收藏  举报

导航