Vue.js is a progressive front-end framework for building user interfaces. Its core library focuses on the view layer, so it does not ship with its own built-in HTTP API. To communicate with a server, we normally bring in a third-party library. The official Vue ecosystem has long recommended Axios for that job. Axios is an excellent HTTP client, uses promises by default, and works both in the browser and on the server side.
That makes Axios a very natural match for Vue.js in projects that need to fetch data from the WordPress REST API and display it in a custom front end. In the examples below, the interface uses Element UI for styling, but the same workflow works just as well with Bootstrap or other front-end frameworks.
Fetch data from the WordPress REST API with Vue.js and Axios
The following example requests the latest WordPress posts through the REST API and displays them in card form on the front end.
<template>
<el-row v-if="posts && posts.length">
<el-col :span="8" v-for="post of posts">
<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">操作按钮</el-button>
</div>
</div>
</el-card>
</el-col>
</el-row>
</template>
<script>
// First import axios
import axios from 'axios';
export default {
data: () => ({
posts : [],
errors: []
}),
// Fetch the data after the component is created
created() {
axios.get('http://abc.dev/wp-json/wp/v2/posts')
.then(response => {
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>
Submit front-end form data to WordPress with Vue.js and Axios
The next example is a basic front-end post submission form. After the user clicks the submit button, the form publishes a draft post to WordPress through the REST API. Because the request is being sent to the same site, the simplest authentication method is to use a nonce. That nonce needs to be exposed to the front end first, so Axios can send it back in the request header.
Start by adding the following code to your theme’s functions.php file:
add_action( 'wp_enqueue_scripts', 'rest_theme_scripts' );
function rest_theme_scripts() {
wp_localize_script( 'jquery', 'wp', [
'nonce' => wp_create_nonce( 'wp_rest' ),
] );
}
That code exposes a JavaScript object named wp to the page. We can then read the nonce with wp.nonce and send it in the Axios headers. The REST API validates that nonce before accepting the post data.
<template>
<el-form ref="form" :model="form" label-width="80px">
<el-c-alert v-if="message.show" :title="message.title" :type="message.type"></el-c-alert>
<el-form-item label="文章标题">
<el-input v-model="form.title"></el-input>
</el-form-item>
<el-form-item label="文章摘要">
<el-input type="textarea" v-model="form.excerpt"></el-input>
</el-form-item>
<el-form-item label="文章内容">
<el-input type="textarea" v-model="form.content"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">立即投稿</el-button>
<el-button>取消</el-button>
</el-form-item>
</el-form>
</template>
<script>
import axios from 'axios';
// Set the nonce in the global axios headers for WordPress REST API authentication
axios.defaults.headers.post['X-WP-Nonce'] = wp.nonce;
export default {
data() {
return {
form : {
title : '',
excerpt : '',
content : '',
},
message: {
title: "",
}
}
}
}
</script>
In the original implementation, a success message is shown after the post is submitted. The article omits the full failure-handling logic for brevity, but in a production app you should absolutely add proper error feedback too.
Create a reusable HTTP module for multiple components
When several modules need to make API calls, it is often cleaner to centralize the HTTP client into a reusable module. Then other components can simply import that module.
<script>
import axios from 'axios';
export const HTTP = axios.create({
baseURL: `http://jsonplaceholder.typicode.com/`,
headers: {
Authorization: 'Bearer {token}'
}
})
</script>
And in another module:
<script>
import {HTTP} from './http-common';
export default {
data: () => ({
posts: [],
errors: []
}),
created() {
HTTP.get(`posts`)
.then(response => {
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>
Once you are comfortable with this development pattern, fetching and submitting front-end data through the WordPress REST API becomes very natural. If you know JavaScript well enough, WordPress can serve as the backend for surprisingly rich front-end applications, including user centers, custom submission systems, and even order-management interfaces.
