Vue – Testing A WordPress API Call

Let’s test the WordPress API call to make sure we are getting data from WordPress:

We will add the following code to our App.vue file (Delete all other code):

*Rember to change the URL to the correct site.

<template>
  <div>
    <ul v-for="post in posts" v-bind:key="post.id">
      <li>{{ post.title.rendered }}</li>
      <p>{{ post.content.rendered }}</p>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      posts: [],
    };
  },
  methods: {
    async getData() {
      try {
        let response = await 
        fetch("https://wordpress-878924-3326173.cloudwaysapps.com/wp-json/wp/v2/posts");
        this.posts = await response.json();
      } catch (error) {
        console.log(error);
      }
    },
  },
  created() {
    this.getData();
  },
};
</script>

We know this has worked if the local host site displays raw posts from our WordPress site.

Here are some great references:

Adding the component:

Let’s revert back our App.vue file to its original code.

Instead of populating the App.vue file, we will create a component that houses our API call for posts.

What is a component? – Components allow us to split the app into “pieces” that call be edited and stored independently. This is great for creating reusable elements that we can call into our app wherever we need them without having to clone or manage more than one code file.

  • We will create the component VuePost.post in our components file.
  • We will then add the API test code from above to the VuePost.vue file.
  • Finally, we will need to update the App.vue file to pull the component into the final app structure.

In the App.vue file, we will add the following:

// In the script tag, we add
import TechPost from './components/TechPost.vue'

// In the template tag, we add. This tells the app where to display the component.
<VuePost />

Send Me A Quick Message!

Subscribe to updates!

Subscribe to get weely updates of Fun Words, Honest Movie Reviews and more!