Nuxt-无法删除事件监听器

时间:2020-05-29 00:28:21

标签: javascript vue.js nuxt.js

我正在使用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;
         }
    }
 },

1 个答案:

答案 0 :(得分:2)

window.document.onscroll = fn实际上与window.addEventListener('scroll', fn)相同,因此stickyScroll() 每个 {{1} }事件。

解决方案是删除scroll的设置,以使箭头函数的内容成为window.document.onscroll的内容,这将允许正确删除处理程序:

stickyScroll