VUE3 实现图片懒加载

104 阅读1分钟

方法一:自定义指令

使用 @vueuse/core 中的 useIntersectionObserver 来实现监听进入可视区域行为

npm i @vueuse/core

封装plugin

// 定义懒加载插件
import { useIntersectionObserver } from '@vueuse/core'
import {type App } from 'vue';

export const lazyPlugin = {
    install(app:App<Element>) {
        // 定义全局指令
        app.directive('img-lazy', {
            mounted(el, binding) { // el:指令绑定的元素 binding:binding.value:图片url
                el.src = "@/assets/LayoutIcon/noImg.png"; // 使用默认图片
                const {stop} = useIntersectionObserver(
                    el,
                    ([{ isIntersecting }]) => {
                        if (isIntersecting) {
                            el.src = binding.value
                            stop() // 手动停止监听,防止内存浪费
                        }
                    },
                )
            }
        })
    }
}

接口文件导入

import { lazyPlugin } from './directives';
app.use(lazyPlugin).mount('#app')

组件使用

<img v-img-lazy="item.picture" alt="">