美文网首页
vue2 使用 IntersectionObserver 实现图

vue2 使用 IntersectionObserver 实现图

作者: 洪锦一 | 来源:发表于2022-09-30 15:58 被阅读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" />
    

    相关文章

      网友评论

          本文标题:vue2 使用 IntersectionObserver 实现图

          本文链接:https://www.haomeiwen.com/subject/phtrartx.html