Using Vue.js and Axios with the WordPress REST API to Fetch and Submit Data

Vue.js is a progressive front-end framework for building user interfaces. Because the core library of Vue.js only focuses on the view layer, Vue.js does not have a built-in HTTP API. If we need to interact with the server, we must introduce a third-party API. The officially recommended HTTP library for Vue.js is Asios. Axios is a great HTTP client library. It uses promises by default and runs on both client and server (which makes it suitable for fetching data during server-side rendering). Asios is easy to use with Vue.js to get data from the WordPress Rest API and then display it via Vue.js. Below we will give an example of how to use Vue.js and Axios withWordPress Rest APIInteract, get and submit data.

In the following example, Element UI based on Vue.js is used to implement the front-end interface style. If you are familiar with other front-end frameworks, you can also use other frameworks (such as BootStrap) to implement the front-end interface style. The effect is the same.

Get data from WordPress Rest API and display it using Vue.js and Axios

The following code fetches the latest WordPress articles through the Rest API and displays them on the front end as cards.

The following code is copied directly from a Vue.js single-file component and pasted directly into the page. No content will be displayed. It needs to be manually mounted on “#APP” or mounted through Vue Router to display articles on the page.
<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>
    // 首先导入 axios 库
    import axios from 'axios';

    export default {
        data: () => ({
            posts : [],
            errors: []
        }),

        // 组件创建后获取数据,如果获取成功,设置 posts 数据,如果失败,设置错误数据
        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 form data to WordPress Rest API using Vue.js and Axios

The example below is a basicWordPress front-end submissionform, after the user clicks “Submit Now”, an article with a draft status will be published to the WordPress backend through the Rest API. Verification is required before submission through the Rest API to the WordPress backend. Since data is submitted on the same site, we can use the most basic “Nonce” verification method. This method first requires setting the nonce to the front end for use by the Axios library. First add the following code to WordPress’ 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' ),
   ] );
}

The above code will set a JavaScript object named “wp” to the head of the page, and then below we can passwp.nonceAccess the random number generated by the WordPress backend and add the random number to the http header of Axios. The Rest API will verify the random number. If the verification is consistent, the submitted data can be saved. If the verification fails, an error message will be returned.

<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';

    // 设置 axios 全局 header nonce 数据,用于 WordPress REST Api 验证,
    // 如果没有这个,提交数据时,会因为权限验证失败而提交不了
    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 = "保存成功";
                         this.message.type = "success";
                         this.message.show = true;
                     })
                     .catch(e => {
                         this.errors.push(e)
                     });
            }
        }

    };
</script>

In the above code, after the user submits successfully, a prompt message indicating that the submission is successful will be displayed. In order to simplify the length of the article, the method for handling failed submissions is not posted, so if the submission fails, there will be no prompt. Friends in need can implement it by themselves.

Create a general http module to facilitate calling in various modules

In order to facilitate the direct call of data in multiple modules, we can also write a general http module, which can be directly introduced when other modules use it. as follows:

<script>
    import axios from 'axios';

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

When used in other modules:

<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>

After becoming familiar with the above development methods, obtaining submitted data on the WordPress front-end page can be done directly through the WordPress Rest API. As long as you are proficient in JavaScript, you can combine it with WordPress to create an application with rich functions and beautiful interface. For example, the front-end user center that WordPress users often look for, and even the shopping cart order system based on WordPress can be developed through the method introduced in this article.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *