简介
Vue3-Lazy 是一个专为 Vue 3 设计的轻量级懒加载库,支持图片、组件、路由等多种懒加载场景。它基于 Intersection Observer API,提供高性能的懒加载解决方案。
特性
- 🚀 基于 Vue 3 Composition API
- 📱 支持移动端和桌面端
- 🎯 精确的可见性检测
- 🔧 高度可配置
- 📦 轻量级,无额外依赖
- 🎨 支持自定义加载状态
- 🔄 支持错误处理和重试机制
安装
npm install vue3-lazy
基本用法
全局注册
import { createApp } from "vue";
import Vue3Lazy from "vue3-lazy";
import App from "./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 | String | – | 图片或资源的 URL |
loading | String | – | 加载中的占位图 |
error | String | – | 加载失败时的占位图 |
onLoad | Function | – | 加载成功回调 |
onError | Function | – | 加载失败回调 |
threshold | Number | 0.1 | 触发阈值 |
rootMargin | String | ‘0px’ | 根元素边距 |
全局配置选项
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;
top: 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: 懒加载不生效怎么办?
- 检查元素是否在视口内
- 确认 Intersection Observer 支持
- 检查 CSS 样式是否正确
- 验证配置参数是否正确
总结: Vue3-Lazy 提供了强大而灵活的懒加载解决方案,通过合理配置和最佳实践,可以显著提升应用性能和用户体验。建议根据具体场景选择合适的配置参数,并注意移动端的特殊处理。
原文链接:https://code.ifrontend.net/archives/1048,转载请注明出处。
评论0