问题描述
在开发时总会遇到由于图片过多而导致加载缓慢的问题,这个时候我们就可以利用图片懒加载技术来实现当图片没有进入视口的时候不加载 进而提高加载速度
解决方案
1.首先下载依赖
npm i @vueuse/core
2.定义全局指令
在main.js 中
1.导入vueuse
import { useIntersectionObserver } from '@vueuse/core'
2. 在代码中定义自定义指令
// 定义全局指令
app.directive('img-lazy', {
mounted(el, binding) {
/*
* el: 指令绑定的元素
* binding: binding.value 绑定的值
*/
useIntersectionObserver(
el,
([{ isIntersecting }]) => {
// console.log(isIntersecting)
if (isIntersecting) {
el.src = binding.value
}
},
)
}
})
在要懒加载的图片上加入自定义指令 v-img-lazy="img"
<img v-img-lazy="img" alt=""/>
其中 img 为你图片的 url 即原本src的值
参考
自定义指令 | Vue.js (vuejs.org)https://cn.vuejs.org/guide/reusability/custom-directives.htmlDay3-05.Home-图片懒加载指令实现_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1Ac411K7EQ/?p=38&vd_source=4df36f5aa7754ac8253dc4f63d3dfe7c