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