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

步骤:

  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()
                        }
                    },
                )
            }
        })
    },
}
相关推荐
下雪天的夏风10 分钟前
TS - tsconfig.json 和 tsconfig.node.json 的关系,如何在TS 中使用 JS 不报错
前端·javascript·typescript
青稞儿16 分钟前
面试题高频之token无感刷新(vue3+node.js)
vue.js·node.js
diygwcom22 分钟前
electron-updater实现electron全量版本更新
前端·javascript·electron
volodyan25 分钟前
electron react离线使用monaco-editor
javascript·react.js·electron
^^为欢几何^^34 分钟前
lodash中_.difference如何过滤数组
javascript·数据结构·算法
Hello-Mr.Wang39 分钟前
vue3中开发引导页的方法
开发语言·前端·javascript
程序员凡尘1 小时前
完美解决 Array 方法 (map/filter/reduce) 不按预期工作 的正确解决方法,亲测有效!!!
前端·javascript·vue.js
编程零零七4 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
北岛寒沫5 小时前
JavaScript(JS)学习笔记 1(简单介绍 注释和输入输出语句 变量 数据类型 运算符 流程控制 数组)
javascript·笔记·学习
everyStudy5 小时前
JavaScript如何判断输入的是空格
开发语言·javascript·ecmascript