Search code examples
javascriptvue.jsvuejs2axioswordpress-rest-api

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>

Solution

  • 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);
                    })