实现图片懒加载
- 构建自定义指令
- 利用IntersectionObserver完成监测(此处我们直接用vueUse的useIntersectionObserver )
//directive/index.js
// 图片一开始不加载,等到将要看到的时候再加载
import { useIntersectionObserver } from "@vueuse/core"
const imgLazy = {mounted(el) {//1.缓存当前的图片路径const catchSrc = el.src//2.把img.src变为占位图el.src = "占位图地址"//3.监听将要看到的const { stop } = useIntersectionObserver(el, ([{ isIntersecting }]) => {if(isIntersecting) {//4.渲染图片el.src = catchSrc//5.停止监听stop()} })}
}export default {// 在main.js中通过app.use使用install: (app) => {app.directive('imgLazy', imgLazy)}
}
组件中使用
<img v-imgLazy src="图片地址"/>