Vue3-Lazy 是一个专为 Vue 3 设计的轻量级懒加载库,支持图片、组件、路由等多种懒加载场景。它基于 Intersection Observer API,提供高性能的懒加载解决方案。 总结: Vue3-Lazy 提供了强大而灵活的懒加载解决方案,通过合理配置和最佳实践,可以显著提升应用性能和用户体验。建议根据具体场景选择合适的配置参数,并注意移动端的特殊处理。简介
特性
安装
npm install vue3-lazy
基本用法
全局注册
import { createApp } from"vue";
importVue3Lazyfrom"vue3-lazy";
importAppfrom"./App.vue";
const app = createApp(App);
app.use(Vue3Lazy, {
// 全局配置
loading: "/loading.gif",
error: "/error.png",
observerOptions: {
rootMargin: "50px",
},
});
app.mount("#app");图片懒加载
<template>
<div class="image-container">
<!-- 基本用法 -->
<img v-lazy="imageUrl" alt="懒加载图片" />
<!-- 带占位符 -->
<img
v-lazy="{
src: imageUrl,
loading: '/loading.gif',
error: '/error.png',
}"
alt="带占位符的图片"
/>
<!-- 带回调函数 -->
<img
v-lazy="{
src: imageUrl,
onLoad: handleImageLoad,
onError: handleImageError,
}"
alt="带回调的图片"
/>
</div>
</template>
<script setup>
import { ref } from "vue";
const imageUrl = ref("https://example.com/large-image.jpg");
const handleImageLoad = (el) => {
console.log("图片加载成功:", el);
};
const handleImageError = (el) => {
console.log("图片加载失败:", el);
};
</script>API 参考
指令参数
src
loading
error
onLoad
onError
threshold
rootMargin
全局配置选项
app.use(Vue3Lazy, {
// 默认加载图片
loading: "/loading.gif",
// 默认错误图片
error: "/error.png",
// Intersection Observer 配置
observerOptions: {
root: null, // 根元素
rootMargin: "50px", // 根元素边距
threshold: 0.1, // 触发阈值
},
// 自定义加载状态类名
loadingClass: "lazy-loading",
loadedClass: "lazy-loaded",
errorClass: "lazy-error",
// 是否启用调试模式
debug: false,
});高级功能
自定义加载组件
<template>
<div class="custom-loader">
<img v-lazy="imageUrl" alt="自定义加载" />
<div v-if="loading" class="loading-spinner">
<div class="spinner"></div>
<p>加载中...</p>
</div>
</div>
</template>
<script setup>
import { ref } from "vue";
const imageUrl = ref("https://example.com/image.jpg");
const loading = ref(true);
const handleLoad = () => {
loading.value = false;
};
</script>
<style scoped>
.custom-loader {
position: relative;
}
.loading-spinner {
position: absolute;
transform: translateY( 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
.spinner {
width: 40px;
height: 40px;
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>预加载策略
// 预加载配置
const preloadConfig = {
// 预加载距离
preloadDistance: 200,
// 预加载优先级
preloadPriority: 'high',
// 预加载回调
onPreload: (url) => {
console.log('预加载:', url)
}
}
// 使用预加载
<img v-lazy="{
src: imageUrl,
preload: true,
preloadDistance: 300
}" alt="预加载图片" />最佳实践
性能优化
<template>
<!-- 使用合适的阈值 -->
<img
v-lazy="{
src: imageUrl,
threshold: 0.5,
rootMargin: '100px',
}"
alt="优化加载"
/>
<!-- 使用 WebP 格式 -->
<picture>
<source v-lazy="webpUrl" type="image/webp" />
<img v-lazy="fallbackUrl" alt="WebP 图片" />
</picture>
</template>错误处理
<template>
<div class="image-wrapper">
<img
v-lazy="{
src: imageUrl,
error: '/fallback.jpg',
onError: handleError,
retry: 3,
}"
alt="带重试的图片"
/>
</div>
</template>
<script setup>
const handleError = (el, retryCount) => {
console.log(`图片加载失败,重试次数: ${retryCount}`);
if (retryCount >= 3) {
// 显示用户友好的错误信息
el.style.display = "none";
showErrorMessage("图片加载失败,请稍后重试");
}
};
</script>移动端适配
// 移动端配置
const mobileConfig = {
observerOptions: {
rootMargin: "20px", // 移动端使用更小的边距
threshold: 0.1,
},
loading: "/mobile-loading.gif",
preloadDistance: 100, // 移动端预加载距离更短
};常见问题
Q1: 如何禁用懒加载?
<!-- 使用 v-if 条件渲染 -->
<img v-if="shouldLoad" v-lazy="imageUrl" alt="条件加载" />
<!-- 或者使用普通 img 标签 -->
<img :src="imageUrl" alt="直接加载" />Q2: 如何处理动态内容?
<template>
<div v-for="item in items" :key="item.id">
<img v-lazy="item.image" :alt="item.title" />
</div>
</template>
<script setup>
import { nextTick } from "vue";
const updateItems = async () => {
items.value = newItems;
await nextTick();
// 重新初始化懒加载
// vue3-lazy 会自动处理
};
</script>Q3: 如何自定义加载动画?
<template>
<div class="custom-lazy">
<img v-lazy="imageUrl" alt="自定义动画" />
<div class="loading-overlay" v-show="isLoading">
<div class="loading-animation"></div>
</div>
</div>
</template>
<script setup>
import { ref } from "vue";
const isLoading = ref(true);
const handleLoad = () => {
isLoading.value = false;
};
</script>Q4: 懒加载不生效怎么办?
热榜
Vue 3.5 defineModel:让组件开发效率提升 10 倍
Vue 3.5 Watch API 完全指南:性能优化与最佳实践
Vue 3.5 重磅新特性:useTemplateRef 让模板引用更优雅、更高效!
Vue 3.5+ Teleport defer 属性详解:解决组件渲染顺序问题的终极方案
Vue 3.5重磅更新:响应式Props解构,让组件开发更简洁高效
Vue3 Polyfill 完全攻略:解决浏览器兼容性问题的终极指南
零依赖拖拽神器:SortableJS 在 Vue 3 中的最佳实践
vue-virtual-scroller 虚拟滚动库 – 轻松处理10万+数据,性能提升90%
vite+vue3工程-SVG图标配置使用指南——vite-plugin-svg-icons 插件
Nuxt 4.0 完全指南:Nitro 引擎升级与 Composable API 深度解析

優(yōu)網(wǎng)科技秉承"專(zhuān)業(yè)團(tuán)隊(duì)、品質(zhì)服務(wù)" 的經(jīng)營(yíng)理念,誠(chéng)信務(wù)實(shí)的服務(wù)了近萬(wàn)家客戶(hù),成為眾多世界500強(qiáng)、集團(tuán)和上市公司的長(zhǎng)期合作伙伴!
優(yōu)網(wǎng)科技成立于2001年,擅長(zhǎng)網(wǎng)站建設(shè)、網(wǎng)站與各類(lèi)業(yè)務(wù)系統(tǒng)深度整合,致力于提供完善的企業(yè)互聯(lián)網(wǎng)解決方案。優(yōu)網(wǎng)科技提供PC端網(wǎng)站建設(shè)(品牌展示型、官方門(mén)戶(hù)型、營(yíng)銷(xiāo)商務(wù)型、電子商務(wù)型、信息門(mén)戶(hù)型、微信小程序定制開(kāi)發(fā)、移動(dòng)端應(yīng)用(手機(jī)站、APP開(kāi)發(fā))、微信定制開(kāi)發(fā)(微信官網(wǎng)、微信商城、企業(yè)微信)等一系列互聯(lián)網(wǎng)應(yīng)用服務(wù)。