如何在调用函数前检测Vue中所有class为preselect-image的图片已加载?
如何等待所有class为preselect-image的图片加载完成后执行指定函数?
先贴出原Vue模板代码:
<template v-for="(option, oid) in currentStepOptions[preselect.step]"> <div class="preselectbox" v-if="hasOptionImage(option)" v-bind:key="oid"> <div v-bind:class="isSelectedImageClass(preselect.id, option.id)"> <a href="#" v-on:click.prevent="selectOption(option, preselect.id, preselect.step)"> <img v-bind:src="resolveOptionImage(option)" v-bind:data-option-id="option.id" class="preselect-image"> </a> </div> <span class="preselect-name">{{ option.description }}</span> <span v-if="optionHasInformation(option)" class="">{{ option.information }}</span> </div> <div v-else class="preselectbox text-only" v-bind:key="oid"> <div class="preselect-text" v-bind:class="isSelectedClass(preselect.id, option.id)" v-on:click="selectOption(option, preselect.id, preselect.step)"> {{ option.description }} </div> </div> </template>
解决方案
核心思路是统计每张目标图片的加载状态,当所有图片(包括加载失败的)都处理完成后,触发指定函数。
1. 给图片绑定加载/错误事件
修改模板中的img标签,添加@load和@error事件,确保无论图片成功还是失败,都能被统计:
<img v-bind:src="resolveOptionImage(option)" v-bind:data-option-id="option.id" class="preselect-image" @load="handleImageComplete" @error="handleImageComplete" >
2. 初始化统计变量
在组件的data中添加两个变量,分别记录已完成加载的图片数和总目标图片数:
data() { return { completedImageCount: 0, totalImageCount: 0 }; }
3. 实时计算总图片数
通过监听currentStepOptions[preselect.step]的变化,每次切换步骤时重新计算需要加载的图片总数,并重置计数:
watch: { 'currentStepOptions[preselect.step]': { immediate: true, // 初始化时立即执行一次 handler(options) { // 过滤出带有图片的选项,得到总图片数 this.totalImageCount = options.filter(opt => this.hasOptionImage(opt)).length; // 重置已完成计数 this.completedImageCount = 0; } } }
4. 实现统计与触发逻辑
编写handleImageComplete方法,每次图片加载/错误时递增计数,当计数等于总图片数时执行目标函数:
methods: { handleImageComplete() { this.completedImageCount++; // 所有图片都已处理完成(成功或失败) if (this.completedImageCount === this.totalImageCount && this.totalImageCount > 0) { // 调用你需要执行的指定函数 this.yourTargetFunction(); } }, yourTargetFunction() { // 这里替换成你的业务逻辑 console.log('所有preselect-image图片已处理完成!'); } }
可选优化:防止重复触发
如果需要在每次步骤切换时都重新触发逻辑,上面的重置计数已经处理好了;如果只需要触发一次,可以在执行完目标函数后添加标记,避免重复执行。
内容的提问来源于stack exchange,提问作者Adam
相关产品推荐
相关产品推荐

