纯vue实现图片懒加载实现思路
实现方案:用api IntersectionObserve监听器,当元素进入可视区域内,便会触发回调函数。
实现思路:
①给对应的懒加载容器设置ref属性
②使用 this.$nextTick 在Vue实例更新DOM后执行。,确保在组件的模板渲染完成之后再开始执行相关的DOM操作,以避免出现意外的问题。
if (this.$refs.imgBoxCard1) 检查是否存在名为 imgBoxCard1 的DOM(图片容器),确保只有在图片容器存在的情况下才创建 IntersectionObserver 对象并开始观察。
如果存在 imgBoxCard1,则创建一个新的 IntersectionObserver 对象,传递给它一个回调函数 this.onObserve 和一个配置对象:
配置对象包括 root 和 threshold 属性:
root: null 表示观察器的根元素是视窗本身。
threshold : 0 表示只要目标元素的任何部分进入视窗,就会触发回调。
最后,通过 this.observer.observe(this.$refs.imgBoxCard1) 开始观察图片容器,以便在图片容器进入视图时触发 this.onObserve 回调函数,从而实现图片的懒加载
**observe 和 unobserve 是 IntersectionObserver 的两个方法,用于开始和停止观察目标元素的可见性状态变化。
③onObserve 方法会检查 IntersectionObserver 的回调中的 entries 参数,如果 entry 的 intersectionRatio 大于 0,说明目标元素进入视图。(entry.intersectionRatio > 0),触发onObserve方法,此时开始加载图片。
当目标元素进入视图时,通过 this.$refs 获取图片容器的引用,并根据传入的 imgSrc 或 itemId 加载相应的图像。加载后,观察者会停止观察,以避免不必要的重复加载(this.observer.unobserve(entry.target))解除对目标元素的观察。
entry {
target:被观察的目标元素本身。
intersectionRatio:表示目标元素与视窗的交叉比例,如果元素完全可见,则 intersectionRatio 为 1,如果元素不可见,则为 0,如果元素部分可见,则在 0 和 1 之间。
}
图片加载时,会调用 onImgLoad 方法,将 loaded 数据设置为 true,并显示图像。
如果图片加载出错,会调用 onImgError 方法,将 loaded 数据设置为 false,并隐藏图像。
通过使用 IntersectionObserver,当用户滚动页面使得小卡片进入可见区域时,图片会被加载,从而实现图片的懒加载效果。
示例代码:
<div class="img-box" ref="imgBoxCard1">
<i v-if="!loaded" class="iconfont icon-tupian" style=""><!--图片加载中--></i>
<img alt="/" ref="img" style="display: none;" @load="onImgLoad" @error="onImgError"/>
</div>
methods: {
onImgLoad() {
this.loaded = true;
this.$refs.img.style.display = "block";
},
onImgError() {
this.loaded = false;
this.$refs.img.style.display = "none";
},
onObserve(entries) {
const entry = entries[0];
if (entry && entry.intersectionRatio > 0) {
this.$refs.img.src = this.imgSrc && this.imgSrc.includes("/item/") ? this.imgSrc : `/item/${this.itemId}/${this.imgSrc}`
this.observer.unobserve(entry.target);
}
},
mounted() {
if (this.labUtils) {
this.lab_utils = {...this.labUtils}
}
this.$nextTick(() => {
if (this.$refs.imgBoxCard1) {
this.observer = new IntersectionObserver(this.onObserve, {
root: null,
threshold: 0
});
this.observer.observe(this.$refs.imgBoxCard1);
}
});