原创
用Vue 3编写图片懒加载自定义指令的完整指南
在Web开发中,图片懒加载是提高页面加载速度和性能的重要技术之一。而Vue 3作为当下流行的前端框架,提供了方便易用的自定义指令功能,可以轻松实现图片懒加载效果。本文将介绍如何使用Vue 3编写一个图片懒加载的自定义指令,而且完全不依赖第三方包。
1. 准备工作
首先,确保你已经创建了一个Vue 3项目,并且已经安装了TypeScript。接下来,我们将开始编写自定义指令。
2. 编写自定义指令
我们给指令取名为LazyLoadDirective。下面是指令的实现代码:
TypeScript
123456789101112131415161718
// src/directives/lazyload.ts
import { Directive, App, ObjectDirective } from 'vue';
export const LazyLoadDirective: ObjectDirective = {
mounted(el: HTMLElement) {
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target as HTMLImageElement;
img.src = img.dataset.src!;
observer.unobserve(img);
}
});
});
observer.observe(el);
},
};
3. 全局注册自定义指令
在Vue 3中,通过app.directive来创建自定义指令。在 main.ts中调用LazyLoadDirective函数:
TypeScript
12345678910
import { createApp } from 'vue'
import { LazyLoadDirective } from './directives/lazyload'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.directive('lazyload', LazyLoadDirective)
app.mount('#app')
4. 实现步骤
- 创建一个自定义指令,命名为
lazyload。 - 在指令的
mounted生命周期钩子中,使用IntersectionObserver监听图片是否进入视口。 - 如果图片进入视口,则将
src属性设置为图片真实的地址,从而实现图片懒加载效果。
5. 占位图与错误图
为了提高用户体验,我们可以在图片加载之前显示占位图,图片加载失败时显示错误图。你可以在src属性中设置占位图的地址,以及在onerror事件中设置错误图的地址。
Vue
1234567891011121314151617181920212223242526
<template>
<div class="list">
<div class="item" v-for="item in state.list" :key="item.id">
<img v-lazyload :data-src="item.src" src='/loading.png' :alt="item.alt" @error="handleError">
</div>
</div>
</template>
<script setup lang="ts">
import { reactive } from 'vue'
const state = reactive({
list: [
{ id: 1, src: '1.png', alt: '图片1' },
{ id: 2, src: '2.png', alt: '图片2' },
{ id: 3, src: '3.png', alt: '图片3' },
],
})
const handleError = (event: Event) => {
const img = event.target as HTMLImageElement
// 设置错误图
img.src = '/error.png'
}
</script>
期待你的捷足先登






