<template>
<div>
<img :src="thumbnailSrc" v-if="!isLoaded && thumbnailSrc" ref="thumbnail" />
<img :src="actualSrc" @load="onLoad" v-else ref="actualImage" />
</div>
</template>
<script>
export default {
props: {
actualSrc: {
type: String,
required: true
},
thumbnailSrc: {
type: String,
required: false
}
},
data() {
return {
isLoaded: false
};
},
mounted() {
this.observeIntersection();
},
beforeDestroy() {
this.intersectionObserver && this.intersectionObserver.unobserve(this.$refs.actualImage);
},
methods: {
onLoad() {
this.isLoaded = true;
},
observeIntersection() {
if ('IntersectionObserver' in window) {
this.intersectionObserver = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
this.$refs.actualImage.src = this.actualSrc; // 视区可见时开始加载原图
this.intersectionObserver.unobserve(this.$refs.actualImage);
}
});
},
{ threshold: 0.5 } // 当元素50%出现在视口中时触发
);
this.intersectionObserver.observe(this.$refs.actualImage);
} else {
// 如果浏览器不支持IntersectionObserver,则直接加载原图
this.$refs.actualImage.src = this.actualSrc;
}
}
}
};
</script>
vue中在图片加载时先加载缩略图等待原图加载完成后在加载原图()
最新推荐文章于 2024-09-14 10:01:38 发布
文章详细描述了如何在Vue应用中利用IntersectionObserver实现图片的动态加载,仅在图片进入用户视域50%时加载,以提高用户体验和性能。
摘要由CSDN通过智能技术生成