【问题标题】:Nuxt - Cannot remove Event ListenerNuxt - 无法删除事件监听器
【发布时间】:2020-05-29 00:28:21
【问题描述】:

我正在使用nuxt.js 并有一个滚动条,它可以滚动并停止在我页面上的固定点。

当我点击下一页时,该方法仍在寻找 $ref=nav 并返回 undefined 因为它不再存在 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;
         }
    }
 },

【问题讨论】:

    标签: javascript vue.js nuxt.js


    【解决方案1】:

    window.document.onscroll = fn 实际上与window.addEventListener('scroll', fn) 相同,因此stickyScroll() 每个 scroll 事件添加一个新的事件侦听器。

    解决办法是去掉window.document.onscroll的设置,让箭头函数的内容变成stickyScroll的内容,这样就可以正确的去掉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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      相关资源
      最近更新 更多