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

步骤:

  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()
                        }
                    },
                )
            }
        })
    },
}
相关推荐
花海如潮淹6 分钟前
前端性能追踪工具:用户体验的毫秒战争
前端·笔记·ux
_丿丨丨_5 小时前
XSS(跨站脚本攻击)
前端·网络·xss
天天进步20155 小时前
前端安全指南:防御XSS与CSRF攻击
前端·安全·xss
呼啦啦呼啦啦啦啦啦啦6 小时前
利用pdfjs实现的pdf预览简单demo(包含翻页功能)
android·javascript·pdf
拾光拾趣录8 小时前
括号生成算法
前端·算法
拾光拾趣录8 小时前
requestIdleCallback:让你的网页如丝般顺滑
前端·性能优化
前端 贾公子8 小时前
vue-cli 模式下安装 uni-ui
前端·javascript·windows
拾光拾趣录9 小时前
链表合并:双指针与递归
前端·javascript·算法
@大迁世界9 小时前
前端:优秀架构的坟墓
前端·架构
拼图2099 小时前
element-plus——图标推荐
javascript·vue.js·elementui