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

时间:2020-05-03 16:47:55

标签: javascript vue.js vue-component intersection-observer

这是我第一次使用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>

我该如何解决?(谢谢)

1 个答案:

答案 0 :(得分:1)

您已将/usr/local/bin/的{​​{1}}从以下位置更改:

default

收件人:

options

但是,如果我们查看default: () => { return { root: null, threshold: "0" }; } ,这是IntersectionObserver选项对象的接口:

default: () => ({
  root: 0,
  threshold: "0"
})

lib.dom.d.tsinterface IntersectionObserverInit { root?: Element | null; rootMargin?: string; threshold?: number | number[]; } root时,null默认为视口元素。

因此将其更改回undefined即可使用。