5

It's my first time that i use IntersectionObserver and i followed this doc https://www.netguru.com/codestories/infinite-scroll-with-vue.js-and-intersection-observer . But I'm blocked because of this error

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

this is my trigger component

<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>

How can i fix this?(thanks)

folipso
  • 107
  • 1
  • 8

1 Answers1

1

You've changed the default of options from:

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

to:

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

But if we look into lib.dom.d.ts, here's the interface for IntersectionObserver options object:

interface IntersectionObserverInit {
  root?: Element | null;
  rootMargin?: string;
  threshold?: number | number[];
}

When root is null or undefined, the IntersectionObserver defaults to the viewport element.

So change it back to null and it will work.

tao
  • 82,996
  • 16
  • 114
  • 150
  • You're trying to iterate through a response of a promise as if it was an array, but it's `undefined`. I need more info to tell you more. Could you please create a [mcve]? I suggest codesandbox.io. Btw, in case you missed it, the author of that article linked a [demo](https://codesandbox.io/s/vy4n7nzjk3) which you could get inspiration from. – tao May 03 '20 at 17:52