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

图片懒加载简单来说是指进入页面时非可视区域的图片不加载,目的是提高渲染速度

直接上代码

<template>
    <div class="lazy">
        <img v-lazy="item" width="300px" height="400px" v-for="(item, i) in arrList" :key="i" src="">
    </div>
</template>
let arrList = [
    'https://tse3-mm.cn.bing.net/th/id/OIP-C.PblErH34r4TZEYtrIHP2bAAAAA?w=187&h=333&c=7&r=0&o=5&pid=1.7',
    'https://tse1-mm.cn.bing.net/th/id/OIP-C.cqwDlCQ63kidK9qoKK_GkwHaNK?w=187&h=333&c=7&r=0&o=5&pid=1.7',
    'https://tse2-mm.cn.bing.net/th/id/OIP-C.6ohtlagu9z-P-vXPaxnthQHaLG?w=204&h=306&c=7&r=0&o=5&pid=1.7',
    'https://tse1-mm.cn.bing.net/th/id/OIP-C.Qp74PrYLkMGMIkTehqTdnwHaLG?w=204&h=306&c=7&r=0&o=5&pid=1.7',
]

存放图片地址的数组,通过v-for渲染到页面

const vLazy: Directive = async (el, binding) => {
    const logo = await import('@/assets/logo.svg')
    el.src = logo.default
    const watchItem = new IntersectionObserver((entries) => {
        // intersectionRatio 指 当前元素占据视窗比例 0-1
        if (entries[0].intersectionRatio > 0) {
            // 大于0说明已出现在视窗,可以展示
            el.src = binding.value
            // 结束监听
            watchItem.unobserve(el)
        }
    })
    watchItem.observe(el)
}

IntersectionObserver 接口(从属于 Intersection Observer API)提供了一种异步观察目标元素与其祖先元素或顶级文档视口(viewport)交叉状态的方法。其祖先元素或视口被称为根(root)

当一个 IntersectionObserver 对象被创建时,其被配置为监听根中一段给定比例的可见区域。一旦 IntersectionObserver 被创建,则无法更改其配置,所以一个给定的观察者对象只能用来监听可见区域的特定变化值;然而,你可以在同一个观察者对象中配置监听多个目标元素

属性属性说明
boundingClientRect返回包含目标元素的边界信息
intersectionRatio返回目标元素出现在可视区的比例,范围0~1
intersectionRect用来描述root和目标元素的相交区域
isIntersecting

返回一个布尔值,两种操作均会触发callback:

1. 目标元素出现在root可视区,返回true

2. 从root可视区消失,返回false

rootBounds用来描述交叉区域观察者(intersection observer)中的根
target目标元素:与根出现相交区域改变的元素 (Element)
time返回一个记录从 IntersectionObserver 的时间原点到交叉被触发的时间的时间戳

 

  • 13
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值