定义全局指令用于懒加载

为了节约资源对图片进行懒加载,只有当图片进入视窗之后才开始加载

main.js

//定义全局指令

app.directive('img-lazy',{
    mounted(el,binding){
        //el: 指令绑定的那个元素 img
        //binding:binding.value 指令等于号绑定的表达式的值 图片url
        console.log(el,binding.value)
        useIntersectionObserver(
            el,
            ([{isIntersecting}])=>{
                if(isIntersecting){
                    el.src=binding.value
                }
            },
        )
    }
})

为了节约资源,优化懒加载,将懒加载封装成插件,然后在主函数中对插件进行调用

directives-index.js

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

export const lazyPlugin={
    install (app){
        //懒加载指令逻辑
        app.directive('img-lazy',{
            mounted(el,binding){
                //el: 指令绑定的那个元素 img
                //binding:binding.value 指令等于号绑定的表达式的值 图片url
                console.log(el,binding.value)
                useIntersectionObserver(
                    el,
                    //isIntersectinng是一个布尔值
                    ([{isIntersecting}])=>{
                        console.log(isIntersecting)
                        if(isIntersecting){
                            el.src=binding.value
                        }
                    },
                )
            }
        })
    }
}

main.js

//引入懒加载指令插件并注册
import { lazyPlugin } from './directives'
//调用懒加载插件
app.use(lazyPlugin)

没有停止运行的话,懒加载插件会因为重复监听问题造成内存浪费

directives-index.js

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

export const lazyPlugin={
    install (app){
        //懒加载指令逻辑
        app.directive('img-lazy',{
            mounted(el,binding){
                //el: 指令绑定的那个元素 img
                //binding:binding.value 指令等于号绑定的表达式的值 图片url
                console.log(el,binding.value)
                const {stop}=useIntersectionObserver(
                    el,
                    //isIntersectinng是一个布尔值
                    ([{isIntersecting}])=>{
                        console.log(isIntersecting)
                        if(isIntersecting){
                            el.src=binding.value
                            stop()
                        }
                    },
                )
            }
        })
    }
}

猜你喜欢

转载自blog.csdn.net/clown_sam/article/details/131705934