javascript - 我可以检测到所有图像何时加载,以便将 isLoaded 变量更改为 true 吗?
问题描述
我有以下模板:
<template>
<div v-if='isLoaded'>
<div @click='selectSight(index)' v-for='(sight, index) in sights'>
<img :src="'https://maps.googleapis.com/maps/api/place/photo?maxwidth=300&photoreference=' + sight.photos[0].photo_reference + '&key='">
</div>
</div>
</template>
我想知道是否有可能以某种方式检测所有图像何时加载,以便isLoaded
在发生这种情况时设置为 true?我想避免在加载所有内容之前显示整个 div,这样我就可以避免加载图像的闪烁(其中一些加载得更快,一些加载得更慢)。
<script>
export default {
data(){
return {
sights: null,
isLoaded: false
}
},
mounted() {
axios.get('/getSights/' + this.lat + '/' + this.lng + '/' + this.type + '/' + this.range)
.then(response => {
this.sights = response.data.result.results
this.nextPageToken = response.data.result.next_page_token
}).catch((error) => console.log(error));
}
}
</script>
我试过了:
var images = document.getElementsByClassName('sight-photos');
images.onload = function () {
console.log('hey')
}
但是,当我尝试时,我没有看到控制台消息:
var images = document.getElementsByClassName('sight-photos')[0];
images.onload = function () {
console.log('hey')
}
我确实看到了消息,所以我假设您不能在图像集合上使用 onload?
解决方案
如果您使用v-if指令,则永远不会创建元素并且不会加载图像。但是,您可以在 div 上使用v-show指令来创建 html,但将其隐藏。这里的一种方法是使用一个数组来跟踪所有加载的图像,然后使用它来更新isLoaded属性。
<template>
<div v-show='isLoaded'>
<div @click='selectSight(index)' v-for='(sight, index) in sights'>
<img
:src="'https://maps.googleapis.com/maps/api/place/photo?maxwidth=300&photoreference=' + sight.photos[0].photo_reference + '&key='"
v-on:load="setLoaded(index)"
>
</div>
</div>
<script>
export default {
data(){
return {
sights: null,
loadedSights: []
isLoaded: false
}
},
mounted() {
axios.get('/getSights/' + this.lat + '/' + this.lng + '/' + this.type + '/' + this.range)
.then(response => {
this.sights = response.data.result.results
this.nextPageToken = response.data.result.next_page_token
this.loadedSights = this.sights.map(function(){ return false; });
}).catch((error) => console.log(error));
},
methods: {
setLoaded: function(index){
this.loadedSights[index] = true;
for (var i=0; i< this.loadedSights.length; i++){
if (!this.loadedSights[i]){
this.isLoaded = false;
return
}
}
this.isLoaded = true;
}
}
}
</script>
推荐阅读
- wordpress - 本地 Wordpress 网站 (https) 未从本地网络外部加载
- python - 如何使用输出参数调用 C 函数
- html - 如何扩展按钮的悬停区域以便仍触发下拉?
- wordpress - Wordpress 页面不会从 Google 引荐来源加载,如果我直接浏览到它,加载正常
- javascript - 自动删除特定文件夹中的文件
- three.js - 着色器,不绘制视野内的物体
- javascript - 如何在 Javascript 中替换字符串中的特定单词组合?
- reactjs - 如何更新从处于状态的空数组中提取的输入值?
- node.js - app.post 不工作,使用 console.log 不打印任何内容。感谢你的帮助。(学习速递节点JS)
- diameter-protocol - 海鸥流量生成器。AVP 长度