简体   繁体   中英

Fetch posts from Wordpress Api with Vuejs

I'm trying to fetch posts title form WP API with Vuejs but console throws me an error

Cannot read property 'rendered' of undefined"

I don't know what is a problem. Here is posts component:

<template>

<div class="posts">
            <h1>Posts</h1>
            <ul>
                <li v-for="post in posts" :key="post.id">
                     {{ post.title.rendered  }}
                </li>
            </ul>
        </div>
</template>

<script>

    export default {
        mounted() {
            this.getPosts();
        },

        data() {
            return {
                postsUrl: 'http://localhost:8080/wp-json/wp/v2/posts',
                posts: [],
                postsData: {
                    per_page: 10,
                    page: 1
                },

            }
        },
        methods: {

            getPosts() {
              axios.get(this.postsUrl, {params: this.postsData})
                    .then((response) => {
                        this.posts = response;
                          this.configPagination(response.headers);
                    })
                    .catch( (error) => {
                        console.log(error);
                    });
            },

        }
    }
</script>

the response object in axios includes multiple properties like headers , status and data , in your case the your posts are the data property, so set this.posts = response.data; :

     .then((response) => {
                    this.posts = response.data;
                      this.configPagination(response.headers);
                })

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