无法从 v-for 获取数据且数据为空

Posted

技术标签:

【中文标题】无法从 v-for 获取数据且数据为空【英文标题】:Cannot get data from v-for and the data is null 【发布时间】:2021-04-03 23:24:37 【问题描述】:

我一直坚持使用 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: 无法读取属性 'data' 为空”

发现于

---> 在资源/js/views/Newsfeed.vue 在资源/js/components/App.vue "

我不明白,因为在 Vue.js 开发人员工具中我可以获取数据。循环错了吗?谢谢!

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

谢谢!我也通过更改 this.posts = res.data.data 来解决,循环是 v-for="post in posts"【参考方案2】:

另一个答案是像这样添加加载变量

在数据中: 数据:()=> 返回 帖子:空, 加载:真

在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')
        )
    

【讨论】:

以上是关于无法从 v-for 获取数据且数据为空的主要内容,如果未能解决你的问题,请参考以下文章