6

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)

6
  • Which browser & version are you using? Commented May 3, 2020 at 16:51
  • Google Chrome 81.0.4044.129 Commented May 3, 2020 at 16:52
  • Have you tried this in the created lifecycle method as opposed to mounted? Commented May 3, 2020 at 17:02
  • Yes, same error Commented May 3, 2020 at 17:05
  • it seems that your IntersectionObserver is not defined or not imported properly. Commented May 3, 2020 at 17:16

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 minimal reproducible example? I suggest codesandbox.io. Btw, in case you missed it, the author of that article linked a demo which you could get inspiration from.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.