简体   繁体   English

Nuxt - 无法删除事件监听器

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM