插件的方式实现-图片懒加载-自定义指令判断是否进入可视区域

102 阅读1分钟

useIntersectionObserver :用来处理图片懒加载,判断是否已经滚动到对应的区域 vueuse.org/core/useInt…

import {
    useIntersectionObserver
} from '@vueuse/core'

export const lazyPlugin = {
    install(app) {
        // 图片懒加载自定义指令
        app.directive('img-lazy', {
            mounted(el, binding) {
                const {
                    stop
                } = useIntersectionObserver(
                    el,
                    ([{
                        isIntersecting // 布尔值
                    }]) => {
                        // 进入可视区域
                        if (isIntersecting) {
                            el.src = binding.value
                            stop() // 停止监听 提升性能
                        }
                    },
                )
            }
        })
    }
}
import {
    lazyPlugin
} from '@/directives'

app.use(lazyPlugin)
使用
<img v-img-lazy="item.picture" alt="" />