Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with Intersection Observer in vue.js

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)

like image 998
folipso Avatar asked Nov 07 '22 08:11

folipso


1 Answers

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.

like image 155
tao Avatar answered Nov 12 '22 16:11

tao