vue2 使用 IntersectionObserver 实现图

2022-09-30  本文已影响0人  洪锦一

/src/directives/lazy.js

export default {
    // vue2 inserted
    // vue3 mounted
    inserted(el) {
        const imgSrc = el.src
        el.src = ''

        // 观察者
        const obServer = new IntersectionObserver(([{ isIntersecting }]) => {
            // 元素出现在可视区域,和离开可视区域被触发
            if (isIntersecting) {
                // 加载图片
                el.src = imgSrc
                // 停止观察
                obServer.unobserve(el)
            }
        })
        obServer.observe(el)
    }
}

main.js 全局注册指令

import lazy from "./directives/lazy"
Vue.directive('lazy', lazy)

页面使用

<img v-lazy  src="https://t7.baidu.com/it/u=2141219545,3103086273&fm=193&f=GIF" />
上一篇下一篇

猜你喜欢

热点阅读