將方法寫出來,銷毀在beforeDestroy寫。
mounted(){ window.addEventListener("scroll",this.handleFun), }, methods:{ handleFun(){ let t = document.documentElement.scrollTop || document.body.scrollTop; let tabBar = document.getElementById("tabBar"); if( t >= 88 ) { tabBar.style.cssText="position:fixed;top:0;z-index:999"; } else { tabBar.style.position="relative"; } } }, beforeDestroy(){ window.removeEventListener("scroll",this.handleFun) }
以下幾種方法同樣有效:
//把scroll的匿名函數掛到this上 mounted(){ this.tabScroll(); }, methods:{ tabScroll(){ this.scroll_ = function () { let t = document.documentElement.scrollTop || document.body.scrollTop; console.log(t); let tabBar = document.getElementById("tabBar"); if( t >= 88 ) { tabBar.style.cssText="position:fixed;top:0;z-index:999"; } else { tabBar.style.position="relative"; } } window.addEventListener("scroll",this.scroll_); }, }, destroyed(){ window.removeEventListener("scroll",this.scroll_); }
methods:{ tabScroll(){ window.addEventListener("scroll",this.handleScroll); }, handleScroll(){ let t = document.documentElement.scrollTop || document.body.scrollTop; console.log(t); let tabBar = document.getElementById("tabBar"); if( t >= 88 ) { tabBar.style.cssText="position:fixed;top:0;z-index:999"; } else { tabBar.style.position="relative"; } } }, mounted(){ this.tabScroll(); }, beforeDestroy(){ window.removeEventListener("scroll",this.handleScroll); }
這里有一點需要注意:
給vue組件綁定scroll
事件,如果直接在 mounted
鈎子中寫window.addEventListener("scroll",handleFun()),
則頁面並不會執行scroll
事件,原因如下:
- 要銷毀
handleFun
的話,得把handleFun
寫在method
中 - 應該是
window.addEventListener("scroll",this.handleFun)
和window.removeEventListener("scroll",this.handleFun)
, - 而不是
window.addEventListener("scroll",this.handleFun())
和window.removeEventListener("scroll",this.handleFun())
第二個參數應該是一個function,而不是執行它。