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

步骤:

  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()
                        }
                    },
                )
            }
        })
    },
}
相关推荐
IT_陈寒14 分钟前
Vue的数组更新把我坑惨了
前端·人工智能·后端
于航27 分钟前
分层上下文压缩,幻觉检测,错误累积概要
前端
数据掘金29 分钟前
鸿蒙统计的权限弹窗怎么适配?
前端
数据掘金32 分钟前
鸿蒙统计的多设备协同数据怎么打通?
前端
尘中远33 分钟前
Qwt7的曲线渲染平滑实现:高斯卷积、Savitzky-Golay 回归与特征保护
前端
咖啡无伴侣35 分钟前
1. 别再手动改代码格式了!Vue3 项目工程化规范搭建实战
vue.js·架构
Fly1 小时前
我来提需求,你带着 Codex 做项目:AI 全栈课程开始实战了
前端
集智飞行2 小时前
解决mavros2 ros2版本cpu占用高的问题
java·服务器·前端
w2sfot3 小时前
【JS加密在线】jsjiami.online(让JavaScript 更安全!)
开发语言·javascript·安全
HSunR3 小时前
ruoyi 若依 自定义注解 参数校验
java·前端·数据库