In Vue.js, the Vue-Lazyload library provides a directive that allows you to lazy load images. Lazy loading is a technique used to defer loading of non-critical resources at page load time. This can help improve page load performance by only loading images when they are about to enter the viewport.
Here’s how you can use the Vue-Lazyload directive in Vue.js:
1. Install Vue-Lazyload via npm or yarn:
npm install vue-lazyload --save # or yarn add vue-lazyload
2. Import Vue-Lazyload and use it as a plugin in your Vue.js application. You can do this in your main entry file (e.g., `main.js`):
javascript
import Vue from 'vue'; import VueLazyload from 'vue-lazyload'; Vue.use(VueLazyload);
3. Now, you can use the `v-lazy` directive in your Vue components to lazy load images. Simply replace the `src` attribute of your `img` tag with `v-lazy`, and specify the URL of the image you want to lazy load in the `data-src` attribute:
v.html
<template> <div> <img v-lazy="imageUrl" alt="Lazy-loaded Image"> </div> </template> <script> export default { data() { return { imageUrl: 'URL_OF_YOUR_IMAGE_TO_LAZY_LOAD' }; } }; </script>
In this example:
1. The `v-lazy` directive is applied to the `img` tag, indicating that it should be lazy-loaded.
2. The `imageUrl` data property contains the URL of the image you want to lazy load. This URL is bound to the `src` attribute of the `img` tag, and it will be loaded lazily when the image is about to enter the viewport.
That’s it! Now, Vue-Lazyload will handle the lazy loading of images for you, improving the performance of your Vue.js application by deferring the loading of images until they are needed.