[英]Nuxt - Cannot remove Event Listener
I'm using nuxt.js
and have a scroller that scrolls and stops at a fixed point on my page.我正在使用
nuxt.js
并有一个滚动条,可以滚动并停止在我页面上的固定点。
When I click to the next page, the method is still looking for the $ref=nav
and is coming back undefined because it is not there anymore Cannot read property 'getBoundingClientRect' of undefined
当我单击下一页时,该方法仍在寻找
$ref=nav
并返回未定义,因为它不再存在Cannot read property 'getBoundingClientRect' of undefined
I can add the eventListener but cannot remove the eventListener.我可以添加 eventListener 但不能删除 eventListener。
Listener听众
mounted(){
window.addEventListener('scroll', this.stickyScroll);
},
beforeDestroy(){
window.removeEventListener('scroll', this.stickyScroll);
}
Scroller滚动条
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
is effectively the same as window.addEventListener('scroll', fn)
, so stickyScroll()
adds a new event listener for every scroll
event. window.document.onscroll = fn
实际上与window.addEventListener('scroll', fn)
相同,因此stickyScroll()
为每个scroll
事件添加了一个新的事件监听器。
The solution is to remove the setting of window.document.onscroll
so that the contents of the arrow function becomes the contents of stickyScroll
, which would allow the proper removal of the handler:解决方案是删除
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.