无法从 v-for 获取数据,数据为空
2020-12-26
533
我被困在通过 Axios 使用 Vue.js 从数据库获取数据。在 Vue.js 开发人员工具中,我可以像这样从我的数据库中获取数据:
但是当我像这样使用
v-for
循环时:
<template>
<div class="flex flex-col items-center py-4">
<NewPost></NewPost>
<Post v-for="(post,i) in posts.data" :post="post" :key="i"/>
</div>
</template>
<script>
import NewPost from "../components/NewPost";
import Post from "../components/Post";
export default {
name: "Newsfeed",
components: {
NewPost,
Post
},
data: () => {
return {
posts: null
}
},
mounted() {
axios.get('/api/posts').then(res => {
this.posts = res.data
console.log(this.posts)
}).catch(error => {
console.log('Unable to fetch posts')
})
}
}
</script>
<style scoped>
</style>
控制台显示
"[Vue warn]: Error in render: "TypeError: Cannot read property 'data' of null"
found in
---> at resources/js/views/Newsfeed.vue at resources/js/components/App.vue "
我不明白,因为在 Vue.js 开发人员工具中我可以获取数据。循环错误吗?谢谢!
2个回答
使用空数组初始化该嵌套字段,如:
data: () => {
return {
posts: {
data:[]
}
}
},
Boussadjra Brahim
2020-12-26
另一个答案是像这样添加加载变量
在数据中: data: () => { return { posts: null, loading: true }
在 mounted() 中
mounted() {
axios.get('/api/posts').then(res => {
this.posts = res.data
this.loading = false
console.log(this.posts)
}).catch(error => {
this.loading = false
console.log('Unable to fetch posts')
})
}
M Muqiit Faturrahman
2020-12-26