简体   繁体   中英

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.

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

I can add the eventListener but cannot remove the 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.

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:

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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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