簡體   English   中英

Nuxt - 無法刪除事件監聽器

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM