Implement lazy loading in Vue 3
In modern front-end development, lazy loading is an important technology to improve application performance and user experience, especially when dealing with larger images or long list data. Lazy loading means that resources are loaded only when the user needs it, which helps reduce initial loading time and improve response speed. This article will use Vue 3 and its newly launched setup syntax sugar to implement lazy loading functions and provide specific sample code to help everyone better understand.
1. The principle of lazy loading
The basic principle of lazy loading is to monitor the viewport through JavaScript, and the content of the element is loaded only when the user scrolls to an element. For example, in a page with a large number of pictures, only the visible part of the picture is loaded during initial loading, and the remaining pictures are loaded when the user scrolls down.
2. Preparation
First, we need to create a new Vue 3 project. If you don't have a project yet, you can create a new project through the Vue CLI using the following command:
npm install -g @vue/cli vue create lazy-load-demo cd lazy-load-demo npm run serve
Next, installIntersection Observer
, Although this API is natively supported, in order to better support old browsers, we can use a polyfill:
npm install intersection-observer
In yourIntroduce this polyfill in the file:
import 'intersection-observer';
3. Implement lazy loading components
We will create a name calledComponents, utilizing
Intersection Observer
to implement lazy loading. Create component files:
<template> <div ref="imageRef" class="lazy-load-image"> <img v="isVisible" :src="src" :alt="alt" @load="onLoad" @error="onError" /> <div v-else class="placeholder">Loading...</div> </div> </template> <script> import { ref, onMounted, onBeforeUnmount } from 'vue'; export default { props: { src: { type: String, required: true, }, alt: { type: String, default: 'Image', }, }, setup(props) { const imageRef = ref(null); const isVisible = ref(false); let observer = null; const loadImage = (entries) => { (entry => { if () { = true; // Set the image to be visible (); // Unobserve after loading } }); }; onMounted(() => { observer = new IntersectionObserver(loadImage); if () { (); // Observe the image element } }); onBeforeUnmount(() => { if (observer && ) { (); // Clean up on unmount } }); return { imageRef, isVisible, }; }, }; </script> <style scoped> .lazy-load-image { width: 100%; height: auto; position: relative; } .placeholder { width: 100%; height: 200px; /* Specify a height for the placeholder */ display: flex; align-items: center; justify-content: center; background: #f0f0f0; } </style>
In this LazyLoadImage component, we accept two parameters: src and alt. The principle of the component is to monitor the visibility of elements through the IntersectionObserver API. When the image enters the viewport, we update the isVisible variable to true to display the image. If not in the viewport, we display a loaded placeholder.
4. Use lazy loading components
Now we will useLazyLoadImage
Component to implement a lazy loaded image list.
In yourIn the file, add the following code:
<template> <div class="image-list"> <LazyLoadImage v-for="(image, index) in images" :key="index" :src="" :alt="" /> </div> </template> <script> import LazyLoadImage from './components/'; export default { components: { LazyLoadImage, }, data() { return { images: [ { src: '/800/600', alt: 'Cat 1' }, { src: '/801/600', alt: 'Cat 2' }, { src: '/802/600', alt: 'Cat 3' }, { src: '/803/600', alt: 'Cat 4' }, { src: '/804/600', alt: 'Cat 5' }, // More images can be added ], }; }, }; </script> <style> .image-list { display: flex; flex-wrap: wrap; justify-content: center; } </style>
In this component, we importedLazyLoadImage
And usev-for
To render multiple pictures in a loop. Each image will only be lazy to load when entering the viewport, reducing performance overhead.
5. Summary
Using Vue 3's setup syntax sugar and native Intersection Observer, we can easily implement lazy loading. Lazy loading not only improves user experience, but also significantly improves page performance, especially when processing large amounts of images or data.
You can customize lazy loading components as needed, such as adding loading animations, error handling, and placeholder styles.
This is the end of this article about code examples for implementing lazy loading functions in Vue3. For more related content related to lazy loading of Vue3, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!