简体   繁体   中英

Vue.js - v-for not rendering api call response data

I'm trying to render a list of data but it seems like whenever the page loads it doesn't want to display the data. my api call works and grabs everything I need and sets it to my data object. here the code: the blogPosts gets set to an array of objects once its set.

<template>
<div>
    <div class="bw-blog-card" v-for="post in blogPosts" :key="post.id">
        <div class="bw-blog-card__profile"></div>
        <div class="bw-top-blog__top-card">
            <div>
            creator: {{ post.username }}
            </div>
            <div>
                {{ post.created_at }}
            </div>
            <div class="bw-blog-card__card-title">
                {{ post.title }}
            </div>
            <div>
                {{ post.description }}
            </div>
        </div>
    </div>
</div>
</template>

<script>
module.exports = {
    data: () => {
        return {
            blogPosts: []
        }
    },
    methods: {
        getBlogPosts: async () => {
            try {
                let { data } = await axios.get(`/devblog`)
                this.blogPosts = data.data
                console.log(this.blogPosts)
            }
            catch (error) {
                console.error(error)
            }
        }
    },
    created() {
        this.getBlogPosts();
    }
}
</script>

now this works totally fine if I just hard code blogPosts to be an array of objects. can I get some insight onto why it wont work through an api call?

Try to change getBlogPosts: async () => { to async getBlogPosts() { and it should work:

 Vue.config.devtools = false; Vue.config.productionTip = false; let app = new Vue({ el: '#app', data() { return { blogPosts: [] } }, methods: { async getBlogPosts() { try { let { data } = await axios.get(`https://jsonplaceholder.typicode.com/posts`) this.blogPosts = data console.log(this.blogPosts) } catch (error) { console.error(error) } } }, created() { this.getBlogPosts(); } })
 <script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <div id="app"> <div class="bw-blog-card" v-for="post in blogPosts":key="post.id"> <div class="bw-blog-card__profile"></div> <div class="bw-top-blog__top-card"> <div> creator: {{ post.userId }} </div> <div class="bw-blog-card__card-title"> {{ post.title }} </div> <hr/> </div> </div> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM