VueJS如何访问API返回JSON数组中的字段值?
解决Vue中访问API返回数组内post字段的问题
问题原因
API返回的posts字段是数组结构,包含多个post对象,直接使用.id或['id']无法访问——因为数组本身没有这些属性,必须定位到数组内的具体对象。
具体解决方法
访问单个post的title
通过数组索引指定要访问的post(索引从0开始),比如取第一个post的title:{{ posts.posts[0].title }}取第二个post的title:
{{ posts.posts[1].title }}遍历所有post显示title
使用Vue的v-for指令循环渲染数组内的所有post,同时绑定唯一key:<div v-for="post in posts.posts" :key="post.id"> 标题:{{ post.title }} </div>避免未加载时的报错
如果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
相关产品推荐
相关产品推荐

