通过懒加载优化手段优化图片加载,可以做到只有进入视口区域才发生图片请求。
指令用法:在图片img身上绑定v-img-lazy指令,其中img-lazy是自定义指令:
<img v-img-lazy="图片地址">
在项目的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函数来自VueUse,用于判断是否进入视口区域
const { stop } = useIntersectionObserver(
el,
([{ isIntersecting }]) => {
console.log(isIntersecting);
if (isIntersecting) {
// 进入了视口区域
el.src = binding.value
stop()
}
},
)
}
})
}
}
在项目的main.js文件中,加载上面定义的图片懒加载插件:
在组件HomeHot.vue组件中,使用上面定义的图片懒加载自定义指令:
运行项目,到浏览器中查看效果:
图片没有进入视口区域的时候,没有发起网络请求加载图片:
图片进入视口区域,发起了网络请求,来加载图片: