vue.js 中 Intersection Observer 的问题

fol*_*pso 5 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)'"
Run Code Online (Sandbox Code Playgroud)

这是我的触发器组件

<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>
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?(谢谢)

And*_*hiu 1

您已将defaultof更改options为:

default: () => {
  return {
    root: null,
    threshold: "0"
  };
}
Run Code Online (Sandbox Code Playgroud)

到:

default: () => ({
  root: 0,
  threshold: "0"
})
Run Code Online (Sandbox Code Playgroud)

但如果我们查看一下lib.dom.d.ts,就会发现这是 IntersectionObserver 选项对象的接口:

interface IntersectionObserverInit {
  root?: Element | null;
  rootMargin?: string;
  threshold?: number | number[];
}
Run Code Online (Sandbox Code Playgroud)

rootnull或 时undefinedIntersectionObserver默认为视口元素。

所以把它改回来null就可以了。