<template> <img v-lazy="imageUrl" ref="observe" width="100%" height="100%" /> </template> <script> import { urlToBuffer } from "@/utils/utils"; export default { name: "", props: { imgSrc: { require: true, type: String, }, }, data() { return { observer: null, imageUrl: "", }; }, components: {}, created() { this.observer = new IntersectionObserver((entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { // 如果图片进入了可视区域,下载并解密图片 this.fetchAndDecryptImage(this.imgSrc); entry.target.src = require("@/assets/img/yes_bg.svg"); // 解密后取消观察 this.observer.unobserve(entry.target); } }); }); // this.$nextTick(() => { this.observer.observe(this.$refs.observe); }); }, updated() {}, mounted() {}, methods: { fetchAndDecryptImage(url) { // 获取图片的加密数据 urlToBuffer(url) .then((src) => { this.imageUrl = src; }) .catch((error) => { this.imageUrl= "@/assets/img/yes_bg.svg"; }); }, }, computed: {}, watch: {}, }; </script> <style scoped> </style>在这段代码基础上新增不在可视范围停止加载
时间: 2024-02-23 13:56:23 浏览: 24
可以在created生命周期中添加一个判断条件,如果图片已经离开可视区域,则停止加载图片。具体的实现可以在IntersectionObserver的回调函数中添加一个判断条件,如果图片已经离开可视区域,则取消观察。修改后的代码如下所示:
<template>
<img v-lazy="imageUrl" ref="observe" width="100%" height="100%" />
</template>
<script>
import { urlToBuffer } from "@/utils/utils";
export default {
name: "",
props: {
imgSrc: {
require: true,
type: String,
},
},
data() {
return {
observer: null,
imageUrl: "",
};
},
components: {},
created() {
this.observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
// 如果图片进入了可视区域,下载并解密图片
this.fetchAndDecryptImage(this.imgSrc);
entry.target.src = require("@/assets/img/yes_bg.svg");
// 解密后取消观察
this.observer.unobserve(entry.target);
} else if (entry.intersectionRatio <= 0) {
// 如果图片已经离开可视区域,则取消观察
this.observer.unobserve(entry.target);
}
});
});
this.observer.observe(this.$refs.observe);
},
updated() {},
mounted() {},
methods: {
fetchAndDecryptImage(url) {
// 获取图片的加密数据
urlToBuffer(url)
.then((src) => {
this.imageUrl = src;
})
.catch((error) => {
this.imageUrl= "@/assets/img/yes_bg.svg";
});
},
},
computed: {},
watch: {},
};
</script>
<style scoped>
</style>