Skip to content

v-observe

The directive enables you to assign an IntersectionObserver to an element, or collection of elements.

It abstracts dynamically registering and unregistering DOM elements with a provided observer.

The observer is passed in as the directive prop value.

Import

ts
import vObserve from '@leaflink/stash-vue/directives/observe';

Basic usage

The directive covers use cases for element insertion, update, and directive unbind, making it easy to observe a dynamic list where elements might be added or removed from a component's DOM. The directive won't have any control over the observer itself.

vue
<script>
  function handleIntersection(entries) {
    entries.forEach(entry => {
      console.log(entry);
    });
  }

  const observer = new IntersectionObserver(handleIntersection);
</script>

<template>
  <p class="mb-0" v-observe="observer">Observed</p>
</template>

Insertion

When an element is added, if an observer is provided, register the element with the observer.

Update: Not Observed

If an observer is provided, register the element with observer.

Update: Already Observed

If an observer is provided, check to see if that observer is already applied. If it's the same observer, do nothing. If it's different, attempt to unregister the element with the old observer and register with the new observer.

If an observer is removed, attempt to unregister with the old observer.

Directive Unbind

If an observer exists, attempt to unregister with the old observer.


Source and credit: https://blog.parametricstudios.com/posts/vue-directive-intersection-observer