Words etch cherished moments.
OG

用Vue 3编写图片懒加载自定义指令的完整指南

2,076 words, 5 min read
2021/10/22 AM
553 views

在Web开发中,图片懒加载是提高页面加载速度和性能的重要技术之一。而Vue 3作为当下流行的前端框架,提供了方便易用的自定义指令功能,可以轻松实现图片懒加载效果。本文将介绍如何使用Vue 3编写一个图片懒加载的自定义指令,而且完全不依赖第三方包。

#1. 准备工作

首先,确保你已经创建了一个Vue 3项目,并且已经安装了TypeScript。接下来,我们将开始编写自定义指令。

#2. 编写自定义指令

我们给指令取名为LazyLoadDirective。下面是指令的实现代码:

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
// 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函数:

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
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. 实现步骤

  1. 创建一个自定义指令,命名为lazyload
  2. 在指令的mounted生命周期钩子中,使用IntersectionObserver监听图片是否进入视口。
  3. 如果图片进入视口,则将src属性设置为图片真实的地址,从而实现图片懒加载效果。

#5. 占位图与错误图

为了提高用户体验,我们可以在图片加载之前显示占位图,图片加载失败时显示错误图。你可以在src属性中设置占位图的地址,以及在onerror事件中设置错误图的地址。

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
<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>
Published at2021/10/22 AMinCode
#Vue
Creative Commons BY-NC 4.0
https://zhangwurui.cn/article/76
0/0comments
Guest
Start the discussion...
Be the first to comment