[英]Nuxt - Cannot remove Event Listener
我正在使用nuxt.js
並有一個滾動條,可以滾動並停止在我頁面上的固定點。
當我單擊下一頁時,該方法仍在尋找$ref=nav
並返回未定義,因為它不再存在Cannot read property 'getBoundingClientRect' of undefined
我可以添加 eventListener 但不能刪除 eventListener。
聽眾
mounted(){
window.addEventListener('scroll', this.stickyScroll);
},
beforeDestroy(){
window.removeEventListener('scroll', this.stickyScroll);
}
滾動條
stickyScroll(){
window.document.onscroll = () => {
let navBar = this.$refs.nav;
let navBarXPosition = navBar.getBoundingClientRect().x;
let navScrollSpy = this.$refs.navScrollSpy;
let navScrollSpyXPosition = navScrollSpy.getBoundingClientRect().bottom;
if(window.scrollY > navBarXPosition && navScrollSpyXPosition > 25){
this.active = true;
} else {
this.active = false;
}
}
},
window.document.onscroll = fn
實際上與window.addEventListener('scroll', fn)
相同,因此stickyScroll()
為每個scroll
事件添加了一個新的事件監聽器。
解決方案是刪除window.document.onscroll
的設置,以便箭頭 function 的內容成為stickyScroll
的內容,這將允許正確刪除處理程序:
stickyScroll() {
let navBar = this.$refs.nav;
let navBarXPosition = navBar.getBoundingClientRect().x;
let navScrollSpy = this.$refs.navScrollSpy;
let navScrollSpyXPosition = navScrollSpy.getBoundingClientRect().bottom;
if (window.scrollY > navBarXPosition && navScrollSpyXPosition > 25) {
this.active = true;
} else {
this.active = false;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.