Strapi返回对象数据无法通过Vue的v-for渲染问题求助
Vue中v-for无法渲染Strapi数据的问题解决
在Vue项目中,使用{{ posts }}可以正常显示从Strapi接口获取的完整对象数据,但用v-for循环渲染时却没有内容显示。
Strapi返回的JSON数据
{ "data": [ { "id": 1, "attributes": { "title": "Post numer jeden", "content": "tresc w poscie numer jeden", "createdAt": "2022-10-27T17:51:40.396Z", "updatedAt": "2022-10-27T17:51:44.406Z", "publishedAt": "2022-10-27T17:51:44.405Z" } }, { "id": 2, "attributes": { "title": "Post numer dwa", "content": "Tresc w poscie numer dwa", "createdAt": "2022-10-27T17:52:06.344Z", "updatedAt": "2022-10-27T17:52:07.669Z", "publishedAt": "2022-10-27T17:52:07.668Z" } } ], "meta": { "pagination": { "page": 1, "pageSize": 25, "pageCount": 1, "total": 2 } } }
用户原Vue代码
<template> <p>{{ posts }}</p> <div v-for="post in posts" :key="post"> <hr /> <h3>{{ post.title }}</h3> <p>dsdsa</p> </div> </template> <script> import axios from "axios"; export default { data() { return { posts: [], }; }, async created() { const res = await axios.get("http://localhost:1337/api/posts"); this.posts = res.data; }, }; </script>
问题原因及修复方法
- 数据结构错误:你把Strapi返回的整个响应对象(包含
data数组和meta信息)赋值给了posts,但v-for需要遍历数组而非对象。应提取响应中的data数组:this.posts = res.data.data; // 只取数组部分 - 属性访问路径错误:Strapi返回的文章字段都嵌套在
attributes对象中,需通过post.attributes.title访问标题,而非直接post.title。 - key值不规范:
:key="post"使用整个对象作为key不符合Vue要求,应使用唯一标识如post.id。
修改后的完整代码
<template> <p>{{ posts }}</p> <div v-for="post in posts" :key="post.id"> <hr /> <h3>{{ post.attributes.title }}</h3> <p>{{ post.attributes.content }}</p> </div> </template> <script> import axios from "axios"; export default { data() { return { posts: [], }; }, async created() { const res = await axios.get("http://localhost:1337/api/posts"); this.posts = res.data.data; // 修正赋值路径 }, }; </script>
内容的提问来源于stack exchange,提问作者Kotiz
相关产品推荐
相关产品推荐

