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

VueJS如何访问API返回JSON数组中的字段值?

解决Vue中访问API返回数组内post字段的问题

问题原因

API返回的posts字段是数组结构,包含多个post对象,直接使用.id或['id']无法访问——因为数组本身没有这些属性,必须定位到数组内的具体对象。

具体解决方法

  1. 访问单个post的title
    通过数组索引指定要访问的post(索引从0开始),比如取第一个post的title:

    {{ posts.posts[0].title }}
    

    取第二个post的title:

    {{ posts.posts[1].title }}
    
  2. 遍历所有post显示title
    使用Vue的v-for指令循环渲染数组内的所有post,同时绑定唯一key:

    <div v-for="post in posts.posts" :key="post.id">
      标题:{{ post.title }}
    </div>
    
  3. 避免未加载时的报错
    如果API请求是异步的,页面初始化时posts.posts可能为空,可添加判断确保数据存在后再访问:

    {{ posts.posts && posts.posts[0].title }}
    

    或者用v-if控制渲染:

    <div v-if="posts.posts && posts.posts.length > 0">
      {{ posts.posts[0].title }}
    </div>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:55:23