March 29, 2022

Interacting with the WordPress REST API Using Vue.js and Axios – Fetching and Submitting Data

In this article, I’ll explore how to use Vue.js together with Axios to interact with the WordPress REST API. I’ll walk through examples of fetching the latest posts from WordPress and submitting form data to create new posts. This guide helps frontend developers integrate modern JavaScript frameworks with WordPress for seamless data communication.


Why Use Vue.js and Axios?

Vue.js is a progressive JavaScript framework focused on building user interfaces. It doesn’t come with a built-in HTTP client, so third-party libraries are needed for AJAX calls. The Vue.js team recommends Axios — a promise-based HTTP client that works both in the browser and in Node.js, making it suitable for SSR (server-side rendering) as well.


Fetching WordPress Posts Using Axios in Vue.js

The following example demonstrates how to fetch the latest blog posts using Axios and display them using Vue.js with Element UI for styling.

Template Code

<template>
  <el-row v-if="posts && posts.length">
    <el-col :span="8" v-for="post in posts" :key="post.id">
      <el-card :body-style="{ padding: '0px' }">
        <div style="padding: 14px;">
          <span>{{ post.title.rendered }}</span>
          <div class="bottom clearfix">
            <time class="time">{{ post.modified }}</time>
            <el-button type="text" class="button">Action</el-button>
          </div>
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>




Script Code

jsCopyEdit<script>
import axios from 'axios';

export default {
  data() {
    return {
      posts: [],
      errors: []
    };
  },
  created() {
    axios.get('http://abc.dev/wp-json/wp/v2/posts')
      .then(response => {
        this.posts = response.data;
      })
      .catch(e => {
        this.errors.push(e);
      });
  }
};
</script>
<script>
import axios from 'axios';

export default {
  data() {
    return {
      posts: [],
      errors: []
    };
  },
  created() {
    axios.get('http://abc.dev/wp-json/wp/v2/posts')
      .then(response => {
        this.posts = response.data;
      })
      .catch(e => {
        this.errors.push(e);
      });
  }
};
</script>

Note: This code should be used inside a Vue component and mounted to a DOM element (like #app) or rendered via Vue Router.


Submitting Form Data to WordPress REST API

To submit posts via WordPress REST API, authentication is required. Since this is done on the same domain, the simplest method is using the nonce token generated by WordPress.

Add Nonce in functions.php

add_action( 'wp_enqueue_scripts', 'rest_theme_scripts' );
function rest_theme_scripts() {
   wp_localize_script( 'jquery', 'wp', [
      'nonce' => wp_create_nonce( 'wp_rest' ),
   ]);
}

This will inject a JavaScript object wp.nonce into the page.

Form Submission Template

<template>
  <el-form ref="form" :model="form" label-width="80px">
    <el-alert v-if="message.show" :title="message.title" :type="message.type"></el-alert>
    <el-form-item label="Title">
      <el-input v-model="form.title"></el-input>
    </el-form-item>
    <el-form-item label="Excerpt">
      <el-input type="textarea" v-model="form.excerpt"></el-input>
    </el-form-item>
    <el-form-item label="Content">
      <el-input type="textarea" v-model="form.content"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">Submit Post</el-button>
      <el-button>Cancel</el-button>
    </el-form-item>
  </el-form>
</template>

Script for Submission

<script>
import axios from 'axios';

// Add Nonce to Axios headers
axios.defaults.headers.post['X-WP-Nonce'] = wp.nonce;

export default {
  data() {
    return {
      form: {
        title: '',
        excerpt: '',
        content: '',
      },
      message: {
        title: '',
        type: '',
        show: false,
      }
    };
  },
  methods: {
    onSubmit() {
      axios.post('http://abc.dev/wp-json/wp/v2/posts', {
        title: this.form.title,
        excerpt: this.form.excerpt,
        content: this.form.content,
      })
      .then(response => {
        this.message.title = "Post saved successfully";
        this.message.type = "success";
        this.message.show = true;
      })
      .catch(e => {
        console.error(e);
      });
    }
  }
};
</script>

Creating a Reusable Axios Module

You can abstract your Axios configuration into a shared module to avoid redundancy:

// http-common.js
import axios from 'axios';

export const HTTP = axios.create({
  baseURL: 'http://jsonplaceholder.typicode.com/',
  headers: {
    Authorization: 'Bearer {token}'
  }
});

Usage in another component:

<script>
import { HTTP } from './http-common';

export default {
  data() {
    return {
      posts: [],
      errors: []
    };
  },
  created() {
    HTTP.get('posts')
      .then(response => {
        this.posts = response.data;
      })
      .catch(e => {
        this.errors.push(e);
      });
  }
};
</script>

Conclusion

With Vue.js and Axios, integrating your WordPress backend with a modern frontend becomes straightforward. Whether you’re building a custom user dashboard, frontend post submission system, or even an eCommerce front-end powered by WordPress, the REST API gives you the flexibility to fetch and send data seamlessly.