vue 中注册滚动事件与dom 并无不同
以下配合keep-alive 组件使用
在 mounted 注册滚动事件
1 |
this .handleScroll 获取scrollTop |
1 2 3 |
mounted(){ window.addEventListener( 'scroll' , this .handleScroll); } |
1 2 3 4 |
handleScroll () { let scrollTop = document.body.scrollTop; this .scroll = scrollTop; } |
keep-alive 组件激活时调用。该钩子在服务器端渲染期间不被调用。
1 2 3 4 5 6 7 |
activated() { if ( this .scroll > 0){ window.scrollTo(0, this .scroll); this .scroll = 0; window.addEventListener( 'scroll' , this .handleScroll); } } |
keep-alive 组件停用时调用。该钩子在服务器端渲染期间不被调用。
1 2 3 |
deactivated(){ window.removeEventListener( 'scroll' , this .handleScroll); } |