如何在Vue 2中,当满足特定条件时移除eventListener (window.removeEventListene



代码:-

<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块变为true时,我想停止侦听onScroll方法中的滚动事件。但是,尽管如此,每当我滚动时,即使我试图删除eventListener,也会调用onScroll方法。我甚至创建了一个监视器来删除eventListener,但该方法在滚动时仍然被调用。

如何使用onScroll方法删除滚动eventListener ?

:如果我删除节流和削减_.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);
  },
}

演示

相关内容

  • 没有找到相关文章

最新更新