如何在满足特定条件时删除 Vue 2 中的 eventListener (window.removeEventListener)

How to remove an eventListener (window.removeEventListener) in Vue 2, when certain condition is met

代码:-

<template>
// html
</template>

<script>
import _ from "lodash";

 data() {
    return {
      renderComponent: false,
    };
  },
 watch: {
// when this property is true, want to stop calling scroll event with this.onScroll method
    renderComponent(val) {
      if(val === true) {
        console.log("////////I am removing you");
        window.removeEventListener('scroll', this.onScroll);
      }
    }
  },
 methods: {
    onScroll() {
      console.log("I am called////////");
      let similarTickerHeading = this.$refs.similarTicker;
      if(similarTickerHeading) {
       let margin = similarTickerHeading.getBoundingClientRect().top;
       let innerHeigth = window.innerHeight;
        console.log("Window Screen", innerHeigth);
        console.log("Component located", margin);
       
// when this condition is true, I want to stop listening for the scroll event with this (onScroll method)
       if(margin - innerHeigth < 850) {
          console.log("I should start loading the actual component");
          this.renderComponent = true;
          this.$vs.loading.close("#loader-example > .con-vs-loading");
          // removing eventListener for scrolling with the onScroll Method
          window.removeEventListener('scroll', this.onScroll);
       }
      }
    }
  },
  mounted() {
    this.renderComponent = false;
     this.$vs.loading({
        container: "#loader-example",
        type: "point",
        scale: 0.8,
      });

    this.$nextTick(function() {
      window.addEventListener('scroll', _.throttle(this.onScroll,250));
      this.onScroll();
    })
  },
 beforeDestroy() {
    window.removeEventListener('scroll', this.onScroll);
  },
</script>

在上面的代码中,当 onScroll 方法中的 if 块变为真时,我想停止使用 onScroll 方法监听滚动事件。但是,即使我试图删除 eventListener,每当我滚动时,onScroll 方法仍然会被调用。我什至创建了一个观察者来删除 eventListener,但该方法在滚动时不断被调用。

如何使用 onScroll 方法删除滚动事件监听器?

UPDATE :如果我删除限制并切断 _.throttle,滚动事件会被删除。由于使用_.throttle,我无法移除滚动事件监听器。

传递给 window.addEventListener() 的函数引用必须与传递给 window.removeEventListener() 的引用相同。在您的情况下,有两个不同的引用,因为您用 _.throttle().

包装了其中一个

解决方案

缓存传递给 addEventListener() 的函数引用,以便稍后用于 removeEventListener():

export default {
  mounted() {
              
    this._scrollHandler = _.throttle(this.onScroll, 250)

    this.$nextTick(() => {                        
      window.addEventListener('scroll', this._scrollHandler);
      this.onScroll();
    })
  },
  beforeDestroy() {
                                                    
    window.removeEventListener('scroll', this._scrollHandler);
  },
}

demo