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

518 阅读1分钟

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

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

以下配合keep-alive 组件使用

  1. 在 mounted 注册滚动事件 this.handleScroll 获取 scrollTop

     mounted(){
         window.addEventListener('scroll'this.handleScroll);
     }
     handleScroll () {
         let scrollTop = document.body.scrollTop;this.scroll = scrollTop;
     }
    
  2. keep-alive 组件激活时调用。该钩子在服务器端渲染期间不被调用

        activated() {
            if(this.scroll > 0){
                window.scrollTo(0this.scroll);
                this.scroll = 0;
                window.addEventListener('scroll'this.handleScroll);
            }
        } 
    
  3. keep-alive 组件停用时调用。该钩子在服务器端渲染期间不被调用。

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