Vue 中实现图片加载状态检测和骨架屏动态切换

作者:袖梨 2026-07-15

本文讲解如何在 Vue 3 组合式 API 中精准监听单张图片加载完成状态,结合响应式 ref 和 @load 事件,为每张卡片独立控制骨架屏(Skeleton)显示逻辑,避免因初始值误判导致骨架屏闪退。

本文讲解如何在 vue 3 组合式 api 中精准监听单张图片加载完成状态,结合响应式 ref 和 `@load` 事件,为每张卡片独立控制骨架屏(skeleton)显示逻辑,避免因初始值误判导致骨架屏闪退。

在 Vue 应用中,为提升用户体验,常需在异步资源(如图片)加载完成前展示骨架屏。但若处理不当——例如未正确初始化响应式状态——会导致骨架屏“一闪而过”,即刚渲染即消失,即使图片尚未加载完成。核心问题在于:ref() 无参调用返回 undefined,而 undefined === false 为 false,致使 v-if="isLoaded === false" 条件始终不成立,骨架屏无法按预期显示

✅ 正确做法:为每个卡片独立管理加载状态

不应在父组件 ItemSwiper.vue 中使用单一 isLoaded ref 控制所有卡片,而应让每个 ItemCard 自主维护其图片加载状态。修改如下:

1. 父组件:移除全局 isLoaded,改用插槽 + 条件渲染

<!-- ItemSwiper.vue --><template>  <Swiper    class="swiper"    :breakpoints="swiperOptions.breakpoints"    :pagination="{ clickable: true }"    :loop="true"    :modules="swiperOptions.modules"  >    <!-- 数据加载中 or 某张图片未加载完成时,显示骨架屏占位 -->    <template v-for="recipe in storeRecipes.data" :key="recipe.id">      <SwiperSlide class="swiper__slide">        <ItemCard :data="recipe" />      </SwiperSlide>    </template>    <!-- 数据 pending 时统一显示 3 个骨架屏 -->    <template v-if="storeRecipes.pending">      <SwiperSlide class="swiper__slide" v-for="item in 3" :key="`skeleton-${item}`">        <ItemCardSkeleton />      </SwiperSlide>    </template>  </Swiper></template><script setup>import { onMounted } from 'vue';import { Swiper, SwiperSlide } from 'swiper/vue';import { Pagination } from 'swiper/modules';import { useStoreRecipes } from '@/stores/recipes/storeRecipes.js';import ItemCard from '@/components/ItemCard.vue';import ItemCardSkeleton from '@/components/SkeletonLoaders/ItemCardSkeleton.vue';const storeRecipes = useStoreRecipes();onMounted(() => {  storeRecipes.loadRecipes();});</script>

2. 子组件:每个卡片独立跟踪自身图片加载状态

<!-- ItemCard.vue --><template>  <div class="card">    <div class="card__item">      <!-- 图片加载完成前显示骨架屏内容(可复用 ItemCardSkeleton 结构) -->      <div v-if="!isLoaded" class="card__skeleton">        <div class="card__image--skeleton"></div>        <div class="card__content">          <div class="card__title--skeleton"></div>          <div class="card__text--skeleton"></div>          <div class="card__link--skeleton"></div>        </div>      </div>      <img        v-else        class="card__image"        @load="isLoaded = true"        @error="handleImageError"        :src="getSrc('.jpg')"        :alt="data.alt"      />      <div v-if="isLoaded" class="card__content">        <h2 class="card__title">{{ data.title }}</h2>        <p class="card__text">{{ data.text }}</p>        <router-link class="card__link" :to="{ name: 'Home' }">View more</router-link>      </div>    </div>  </div></template><script setup>import { ref } from 'vue';const props = defineProps(['data']);const isLoaded = ref(false); // ✅ 关键:初始化为 false,而非 undefinedconst getSrc = (ext) => {  return new URL(    `../assets/images/recipe/${props.data.image}${ext}`,    import.meta.url  ).href;};const handleImageError = () => {  console.warn(`Failed to load image for recipe ${props.data.id}`);  isLoaded.value = true; // 错误时也设为 true,避免无限 skeleton};</script><style scoped>.card__skeleton {  display: flex;  align-items: center;  gap: 1rem;}.card__image--skeleton {  width: 120px;  height: 120px;  background: #f0f0f0;  border-radius: 8px;  animation: pulse 1.5s infinite;}@keyframes pulse {  0%, 100% { opacity: 0.6; }  50% { opacity: 1; }}/* 其他 skeleton 样式... */</style>

⚠️ 注意事项与最佳实践

  • 勿共享 ref 实例:每个 ItemCard 必须拥有自己独立的 isLoaded = ref(false),否则所有卡片将同步状态,失去“逐张加载、逐张显示”的效果。
  • 处理加载失败:添加 @error 监听并设置 isLoaded = true,防止图片 404 导致骨架屏永久停留。
  • CSS 骨架动画建议:使用 @keyframes pulse 实现渐变灰度动画,比静态色块更符合现代 UX 规范。
  • 性能优化:若卡片数量极大,可结合 IntersectionObserver 实现图片懒加载,进一步减少首屏压力。

通过以上重构,骨架屏将严格遵循“数据 pending → 显示全局 skeleton;单图未加载 → 显示该卡片 skeleton;单图加载完成 → 立即替换为真实内容”的行为逻辑,彻底解决闪退问题,实现流畅、可控的加载体验。

相关文章

精彩推荐