...

/

Intersection Observer Using Composition API

Intersection Observer Using Composition API

Learn how to implement lazy loading with an Intersection Observer using the Composition API.

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.

Press + to interact
// 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 ...