首页 > 解决方案 > 无法从 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 开发人员工具中我可以获取数据。循环错了吗?谢谢!

标签: javascriptdatabaselaravelapivue.js

解决方案


使用空数组初始化该嵌套字段,例如:

    data: () => {
        return {
            posts: {
                   data:[]
                 }
        }
    },

推荐阅读