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

步骤:

  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()
                        }
                    },
                )
            }
        })
    },
}
相关推荐
孤水寒月2 小时前
基于HTML的悬窗可拖动记事本
前端·css·html
祝余呀2 小时前
html初学者第一天
前端·html
脑袋大大的3 小时前
JavaScript 性能优化实战:减少 DOM 操作引发的重排与重绘
开发语言·javascript·性能优化
速易达网络4 小时前
RuoYi、Vue CLI 和 uni-app 结合构建跨端全家桶方案
javascript·vue.js·低代码
耶啵奶膘4 小时前
uniapp+firstUI——上传视频组件fui-upload-video
前端·javascript·uni-app
JoJo_Way5 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
视频砖家5 小时前
移动端Html5播放器按钮变小的问题解决方法
前端·javascript·viewport功能
lyj1689975 小时前
vue-i18n+vscode+vue 多语言使用
前端·vue.js·vscode
小白变怪兽7 小时前
一、react18+项目初始化(vite)
前端·react.js
ai小鬼头7 小时前
AIStarter如何快速部署Stable Diffusion?**新手也能轻松上手的AI绘图
前端·后端·github