hit counter
WordPress REST API with Vue.js - Easily fetching posts

WordPress REST API with Vue.js - Easily fetching posts

Posted on April 9th, 2018.

In the last few days, I've been building a Vue.js project that will take data from my WordPress site then will display it out on a page.

In this post, I will explain how to do it and I will show you a basic example.

How To

First you'll need a Vue project and a WordPress site. As long as you have both of these you will be good to go 🚀💯

Another thing you will need is Axios, it's the library that we'll use to get posts from our WordPress site. There are other alternatives, like the native fetch function in Javascript, but for this tutorial we will be using Axios.

In your vue component, you'll need to add the following code. It will submit a HTTP GET request to the WordPress API on our site to get the content.

data () {
    return {
      posts: []
    }
  },
  created() {
    axios.get('http://www.iamlittle.co.uk/wp-json/wp/v2/posts').then((response) => { this.posts = response.data; });
  }

Obviously, you will need to change the site url to your own or else you'll be getting the latest posts from Iamlittle instead.

Now that we have inserted that code into our vue component, we need to loop the data. This can be done easilly like this:

<div v-for="post in posts" class="post">
    <h1> <a v-bind:href="post.link" v-html="post.title.rendered"> </h1>
    <p v-html="post.excerpt.rendred"> </p>
    <a v-bind:href="post.link"> Read More </a>
</div>

Now if we were to view the Vue project in a browser you should see it working nicely. Preview

And that's how you get posts from your WordPress site using Vuejs and Axios.

Example

See the Pen WordPress REST API Example by Duncan McClean (@damcclean) on CodePen.