vue.js中的交叉观察器问题

问题描述 投票:1回答:1

[这是我第一次使用IntersectionObserver,并且遵循此文档https://www.netguru.com/codestories/infinite-scroll-with-vue.js-and-intersection-observer。但由于此错误,我被屏蔽了

[Vue warn]: Error in mounted hook: "TypeError: Failed to construct 'IntersectionObserver': The provided value is not of type '(Element or Document)'"

这是我的触发器组件

<template>
  <span ref='trigger'></span>
</template>

<script>
export default {
  props:{
    options:{
      type: Object,
      default: () => ({
        root: 0,
        threshold: "0",
      })
    }
  },
  data(){
    return{
      observer : null
    }
  },
  mounted(){
    this.observer = new IntersectionObserver( entries => {
      this.handleIntersect(entries[0]);
    }, this.options);

    this.observer.observe(this.$refs.trigger);
  },
  destroyed(){
    this.observer.disconnect();
  },
  methods:{
    handleIntersect(entry){
      if (entry.isIntersecting) this.$emit("triggerIntersected");
    }
  }
}
</script>

我该如何解决?(谢谢)

javascript vue.js vue-component intersection-observer
1个回答
0
投票

console.log(this.$refs.trigger)内运行mounted()并确保它不是undefined

尝试使用querySelectorAll来获取元素:

<span class="trigger" ref='trigger'></span>
  mounted(){
    this.observer = new IntersectionObserver(this.observerHandler, this.options)

    const elements = document.querySelectorAll('.trigger')

    elements.forEach(element => {
      this.observer.observe(element)
    })
  },
  destroyed(){
    this.observer.disconnect();
  },
  methods:{
    observerHandler(entries, observer) {
      for (const entry of entries) {
        if (entry.isIntersecting) {
          ...
        }
      }
    },
    handleIntersect(entry){
      if (entry.isIntersecting) this.$emit("triggerIntersected");
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.