Search⌘ K

Intersection Observer Using Composition API

Explore how to use Vue's Composition API to create a reusable custom composable for the Intersection Observer. Understand how this technique improves performance through lazy loading by observing viewport visibility and efficiently managing component rendering.

We'll cover the following...

We’ve implemented lazy loading with an Intersection Observer using the Options API. Let’s look at how we can do it using the Composition API.

Implementation

Create a custom reusable composable called useIntersectionObserver.

JavaScript (JSX)
// useIntersectionObserver.js
import { ref, unref, onMounted, onUnmounted } from 'vue'
export const useIntersectionObserver = (elRef, options = {}, onEntry) => {
let observer = null
let isIntersecting = ref(false)
onMounted(() => {
const $el = unref(el)
if(!($el instanceof HTMLElement))
throw new Error(
'useIntersectionObserver: elRef is not an HTMLElement'
)
const intersectionCallback = entries => {
entries.forEach(entry => {
isIntersecting.value = entry.isIntersecting
if(typeof onEntry === 'function') onEntry(entry)
})
}
observer = new IntersectionObserver(intersectionCallback, options)
observer.observe($el)
})
onUnmounted(() => {
observer?.disconnect()
})
return {
isIntersecting,
observer,
}
}

The reusable useIntersectionObserver composable uses the two onMounted and onUnmounted lifecycle hooks When a component is mounted, it checks if the ref passed is an HTMLElement. If it isn’t, then an error is thrown. ...