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

在Nuxt中使用GraphQL从Strapi获取数据后如何展示name字段

Strapi + Nuxt GraphQL 字段渲染问题解决

问题描述

我正在学习GraphQL,采用Strapi作为后端、Nuxt作为前端开发项目。已完成后端环境搭建,当前正尝试将GraphQL查询结果在前端展示。现有代码可成功返回数据,但无法正确渲染出name字段:使用{{organisation.name}}无内容显示,使用{{organisation.attributes.name}}则出现报错。

前端实现代码

<template>
<div>
<!-- Events are displayed here -->
    <div 
        v-for='organisation in organisations' 
        :key='organisation.id' 
    >
       test {{ organisation }}
    </div>
</div>
</template>
<script>
import gql from "graphql-tag";

export default {
  data() {
    return {

    };
  },
  apollo: {
    organisations: gql`
      query organisations {
        organisations {
            data {
            attributes {
                name
            }
            id
            }
        }
    }`
  }
};
</script>

查询返回结果

test [ { "attributes": { "name": "Organisation 1", "__typename": "Organisation" }, "id": "1", "__typename": "OrganisationEntity" }, { "attributes": { "name": "test2", "__typename": "Organisation" }, "id": "2", "__typename": "OrganisationEntity" } ]
test OrganisationEntityResponseCollection

解决方法

核心问题是遍历对象错误:

  • 查询返回的organisations是包含data数组的响应对象,你直接遍历organisations时,实际遍历的是整个响应集合(即输出里的OrganisationEntityResponseCollection),而非真正的组织数据数组。

修正步骤:

  1. 将v-for的遍历源改为organisations.data,这样才能拿到每个组织的具体数据对象
  2. 修改后即可正常通过{{ organisation.attributes.name }}访问名称字段

修正后的模板代码:

<template>
<div>
    <div 
        v-for='organisation in organisations.data' 
        :key='organisation.id' 
    >
       {{ organisation.attributes.name }}
    </div>
</div>
</template>

如果仍有问题,可在组件的mounted钩子中打印数据结构确认:

mounted() {
  console.log('Organisations data:', this.organisations)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 21:35:22