1

I have an issue using intersect observer with vue3. I want to have the intersect shown and being activated with a v-if. Unfortunately it only works if I write the intersect Observer code in the onUpdated method. If I write it in the onMounted the method addImages() will not fire anymore.

Can you tell me if it is correct to write it in onUpdated? Will that cause that a lot of the same Intersection Observer Objects will be created every time the component updates?

Or should I write the "new Intersection Observer" outside of the onMounted so it doesnt create always new instances?

onUpdated(() => {
  const sections = document.querySelectorAll(".intersectObserver");
  const options = {
    threshold: 1,
  };
  let observer = null;
  setTimeout(() => {
    observer = new IntersectionObserver(function (entries, observer) {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          console.log(entry.target);
          addImages();
        }
      });
    }, options);
    sections.forEach((section) => {
      observer.observe(section);
    });
  }, 2000);

in the template

<div v-if="activateIntersect == true" class="intersectObserver w-full"></div> 
user1664377
  • 393
  • 1
  • 3
  • 13
  • You should implement the observer as a Vue directive - install the observer in the `bind` lifecycle hook and remove it in the `unbind` lifecycle hook of the directive. Take a look at [vue-observe-visibility](https://www.npmjs.com/package/vue3-observe-visibility) – IVO GELOV Aug 12 '22 at 10:09
  • you mean not to use it like but kind of
    . Something like that? Can you give me an example? Binding it like that will keep it updated?
    – user1664377 Aug 17 '22 at 09:16
  • Here is an example implementation as a directive - https://github.com/ManukMinasyan/vue3-observe-visibility – IVO GELOV Aug 17 '22 at 13:45

0 Answers0