>我有以下模板:
<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>