You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxtjs+Graphql+Strapi嵌套对象v-for迭代报错求助

解决Nuxt3 + Strapi + GraphQL中v-for迭代嵌套对象的报错问题

问题根源

你遇到的「Cannot read properties of undefined (reading 'titolo')」错误,核心来自两个问题:

  1. 响应式数据处理错误:useAsyncQuery返回的data是响应式ref对象,你直接写const fotografies = {data},导致模板中fotografies.data指向的是这个ref对象,而非GraphQL返回的fotografies数据结构。
  2. 异步加载未兜底:请求完成前data.value为undefined,直接访问嵌套属性会触发报错。

修正后的完整代码

模板部分

<template>
  <div>
    <!-- 加载状态提示 -->
    <div v-if="pending">加载中...</div>
    <!-- 错误提示 -->
    <div v-if="error" style="color: red">{{ error.message }}</div>
    <!-- 迭代渲染数据 -->
    <div v-for="foto in fotografies.data" :key="foto.id">
      <h2>{{ foto.attributes.titolo }}</h2>
      <!-- 图片渲染做多层兜底 -->
      <img 
        v-if="foto.attributes.immagini.data[0]" 
        :src="foto.attributes.immagini.data[0].attributes.url" 
        :alt="foto.attributes.titolo"
      />
    </div>
  </div>
</template>

脚本部分

<script setup>
const query = gql`query foto {
  fotografies {
    data {
      id
      attributes {
        titolo
        slug
        immagini {
          data {
            attributes {
              url
            }
          }
        }
      }
    }
  }
}`

const { data, error, pending, refresh } = await useAsyncQuery(query)
// 用computed包装,确保响应式同时兜底初始空结构
const fotografies = computed(() => data.value?.fotografies || { data: [] })
</script>

关键修正点

  • 正确提取响应式数据:通过data.value?.fotografies获取GraphQL返回的实际数据,并用computed保持响应式。
  • 初始值兜底:用|| { data: [] }确保请求未完成时,fotografies.data是一个空数组,避免v-for迭代undefined。
  • 状态处理:新增pending和error状态的展示,提升用户体验同时方便调试。

内容的提问来源于stack exchange,提问作者Federico

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 16:05:31