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