How to handle image lazy loading in Vue.js



Image not found!!

Lazy loading images in Vue.js can be achieved using the Intersection Observer API or by using a third-party library such as vue-lazyload. I'll show you both approaches.

1. Using Intersection Observer API:

Firstly, you need to install the vue-lazyload library:

bash
npm install vue-lazyload

Then, in your Vue component:

html
<template> <div> <img v-if="isVisible" v-lazy="imageSource" alt="Lazy Loaded Image" /> </div> </template> <script> import VueLazyload from 'vue-lazyload'; export default { data() { return { isVisible: false, imageSource: 'path/to/your/image.jpg', }; }, directives: { lazy: VueLazyload.directive({ preLoad: 1.3, attempt: 1, }), }, mounted() { this.handleIntersection(); }, methods: { handleIntersection() { const options = { rootMargin: '0px', threshold: 0.5, }; const observer = new IntersectionObserver(this.onIntersection, options); observer.observe(this.$el); }, onIntersection(entries) { entries.forEach(entry => { if (entry.isIntersecting) { this.isVisible = true; } }); }, }, }; </script>

In this example, the v-lazy directive from vue-lazyload is used to lazy load the image when it becomes visible in the viewport. The Intersection Observer is used to detect when the element is in the viewport.

2. Using Intersection Observer API without a library:

If you prefer not to use a library, you can implement lazy loading using the Intersection Observer API directly:

html
<template> <div> <img v-if="isVisible" :src="imageSource" alt="Lazy Loaded Image" /> </div> </template> <script> export default { data() { return { isVisible: false, imageSource: 'path/to/your/image.jpg', }; }, mounted() { this.handleIntersection(); }, methods: { handleIntersection() { const options = { rootMargin: '0px', threshold: 0.5, }; const observer = new IntersectionObserver(this.onIntersection, options); observer.observe(this.$el); }, onIntersection(entries) { entries.forEach(entry => { if (entry.isIntersecting) { this.isVisible = true; } }); }, }, }; </script>

This example achieves the same lazy loading effect without using a third-party library. The image source is bound dynamically based on the visibility state.

Choose the approach that best fits your needs and preferences.