首页 > 解决方案 > 我可以检测到所有图像何时加载,以便将 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?

标签: javascriptvue.jsvuejs2

解决方案


如果您使用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>

推荐阅读