自定义指令实现图片懒加载

步骤:

  1. 自定义指令
  2. 判断图片是否进入视口
  3. 只有进入视口的图片才发送网络请求
  4. 代码优化

自定义指令

main.js

js 复制代码
app.directive('img-lazy', {
    mounted(el,binding) {
    	// el是绑定的img元素,binding.value是图片src
        console.log(el, binding.value)
    }
})

绑定元素:

js 复制代码
<img v-img-lazy="item.picture" :src="item.picture" alt=""/>

判断图片是否进入视口

直接使用 vueuse 的 useIntersectionObserver 方法:useIntersectionObserver

main.js

js 复制代码
import { useIntersectionObserver } from '@vueuse/core'

app.directive('img-lazy', {
	// 挂载完毕
    mounted(el,binding) {
        console.log(el, binding.value)
        // 监听 el 元素,isIntersecting 判断是否进入视口区域
        useIntersectionObserver(
            el,
            ([{ isIntersecting }]) => {
                if (isIntersecting) {
                    el.src = binding.value
                }
            },
        )
    }
})

绑定元素:

通过自定义指令来发送图片网络请求。

js 复制代码
<img v-img-lazy="item.picture" alt=""/>

代码优化

封装自定义懒加载插件

js 复制代码
import {useIntersectionObserver} from "@vueuse/core";

/**
 * 自定义懒加载插件
 * @type {{install(*): void}}
 */
export const lazyPlugin = {
    install(app) {
        app.directive('img-lazy', {
            mounted(el,binding) {
                useIntersectionObserver(
                    el,
                    ([{ isIntersecting }]) => {
                        if (isIntersecting) {
                            el.src = binding.value
                        }
                    },
                )
            }
        })
    },
}

入口文件注册:

js 复制代码
import {lazyPlugin} from "@/directives/index.js";
app.use(lazyPlugin)

禁止重复监听

useIntersectionObserver 中存在一个 stop 方法。通过请求图片资源后调用该方法可以实现禁止重复监听。

js 复制代码
export const lazyPlugin = {
    install(app) {
        app.directive('img-lazy', {
            mounted(el,binding) {
                const {stop} = useIntersectionObserver(
                    el,
                    ([{ isIntersecting }]) => {
                        if (isIntersecting) {
                            el.src = binding.value
                            stop()
                        }
                    },
                )
            }
        })
    },
}
相关推荐
廖松洋(Alina)1 分钟前
03主入口页面与导航结构-鸿蒙PC端Electron开发
前端·javascript·华为·electron·开源·harmonyos·鸿蒙
廖松洋(Alina)3 分钟前
09词根分解与水印展示-鸿蒙PC端Electron开发
前端·javascript·华为·electron·开源·harmonyos·鸿蒙
matrixmind86 分钟前
sindresorhustype-fest:TypeScript 工具类型集合
前端·javascript·其他·typescript
通往曙光的路上12 分钟前
JUCJUCJUC
java·前端·数据库
Swift社区15 分钟前
鸿蒙 PC vs Web:谁才是未来应用形态?
前端·华为·harmonyos
问心无愧051315 分钟前
ctf show web入门54
前端·笔记
西贝爱学习23 分钟前
pdf转TXT文本,适用于文字型PDF;扫描版PDF需要使用OCR(光学字符识别)技术来识别图中的文字
java·服务器·前端
故事和你9125 分钟前
洛谷-【数据结构2-2】线段树1
开发语言·javascript·数据结构·算法·动态规划·图论
ZC跨境爬虫26 分钟前
跟着 MDN 学 HTML day_43:(DocumentFragment 接口详解)
前端·javascript·vue.js·ui·html·音视频
Bigger37 分钟前
mini-cc:用最小的代码,复刻一个“真正能干活”的 AI 编程智能体(并且把架构讲清楚)
前端·ai编程·claude