javascript - 无法从 v-for 获取数据且数据为空
问题描述
我坚持使用 Vue.js 通过 Axios 从数据库中获取数据。在 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 警告]:渲染错误:“TypeError:无法读取 null 的属性‘数据’”
在发现
---> 在资源/js/views/Newsfeed.vue 在资源/js/components/App.vue"
我不明白,因为在 Vue.js 开发人员工具中我可以获取数据。循环错了吗?谢谢!
解决方案
使用空数组初始化该嵌套字段,例如:
data: () => {
return {
posts: {
data:[]
}
}
},
推荐阅读
- flutter - 有没有办法实现像这样具有不同大小的子小部件的gridview?
- ssh - Mobaxterm:如何保持 sftp 连接处于活动状态?
- pandas - 如何使用列名的括号表示法在 Pandas 中返回满足多个条件的布尔系列
- javascript - Toggle 资源组不能 100% 工作
- windows - 如何在 Windows 中设置地精?gradle 和 gobblin 的版本应该是什么?
- ios - 从照片 SwiftUI 中获取图像时内存不足
- c - 在 C 中使用 fgets 时防止溢出字符进入输入缓冲区
- python - Python 3:如何遍历文本文件并找到匹配的关键字?
- log4j - Jena 将级别设置为内部的所有日志记录
- java - JAVA 商店程序没有输出正确的数字