WordPress Post from Front End using REST API and Vue.js - Page 2

Webpack Vue.js CLI

Use vue-cli to download vuejs, webpack and template dependencies and create the project in the root of our plugin folder. Navigate to the wp-content/plugins directory.

Update or install globally as needed.

# update
npm update -g vue-cli

# or install
npm install -g vue-cli

Change to the wordpress plugins directory and use vue-cli to install the webpack-simple template into the new wp-api-vuejs-poc folder. For example,

cd ../

# install the webpack-simple template into
# the existing wp-api-vuejs-poc Target directory

vue init webpack-simple wp-api-vuejs-poc

Here is a tree view of the plugin folders and files at this point. Skip ahead and download or browse the source code if you want.

  • wp-api-vuejs-poc
    • src
      • assets
      • App.vue
      • main.js
    • .bablerc
    • .gitignore
    • class-api-vpoc-page.php
    • index.html
    • package.json
    • README.md
    • webpack.config.js
    • wp-api-vuejs-poc.php

Change back to our new plugin directory, for example wp-api-vuejs-poc.

cd wp-api-vuejs-poc

Install node modules with npm install or npm i.

npm i

Development Build

Since the Vuejs app is running in WordPress, we do not need the webpack-dev-server that is included in the vue-cli webpack-simple template.

Uninstall the webpack-dev-server package with npm uninstall using --save-dev option to update the package.json npm manifest.

npm uninstall webpack-dev-server --save-dev

Update the package.json scripts property so the npm run dev command runs webpack development compilation with watch mode enabled. Watch mode recompiles after every change is saved.

REPLACE

"dev": "cross-env NODE_ENV=development webpack-dev-server --open --inline --hot"

WITH

"dev": "cross-env NODE_ENV=development webpack --watch --progress --colors"

Vue Resource

We are using vue-resource to make the wp-api requests and handle responses. Install with --save-dev to update the package.json npm manifest.

npm i vue-resource --save-dev

Page Slug

A front end page template and respective slug is needed to output the app in WordPress on the front end. Last week, I wrote a quick post with details on how to do this. The slug value, api-test is set in the class-api-vpoc-page.php file.

This proof-of-concept was tested with WordPress permalink settings set to Post name.

Let’s do a build to make sure everything is hooked up properly at this point.

npm run build

After the build, you should now have a dist folder in the plugin root containing the javascript and any other static assets.

Login to WordPress and Activate the plugin. Then navigate to the front end page, for example, http://wordpress.dev:8080/api-test/. You should see the default vue-cli template content.

WordPress api-test Page - Default App build
Default App build

Vue App Component

Open up the src/App.vue file and replace the contents with the following containing our post form, vue model and submit handler.

App.vue
<template>
    <div>
    <h3>Submit New Post</h3>
    <form v-on:submit.prevent="onSubmit">
        <div>
        <label>Title</label>
        <input type="text" v-model="post_title" required aria-required="true">
        </div>
        <div>
        <label>Content</label>
        <textarea rows="8" cols="20" v-model="post_content"></textarea>
        </div>
        <input type="submit" value="Submit">
    </form>
    <div>
</template>

<script>
import Vue from './main.js'

export default {
    data() {
        return {
            post_title: null,
            post_content: null
        }
    },
    methods: {
    onSubmit: function () {
        Vue.http.post(
            wp_api_vuejs_poc.rest_url + 'wp/v2/posts',
            {
            title: this.post_title,
            content: this.post_content
            }
        ).then(response => {
        console.log( response );
        alert( wp_api_vuejs_poc.success );
        }, response => {
        console.log( response );
        alert( wp_api_vuejs_poc.failure );
        })
    }
    },
}
</script>

Open up the src/main.js file and replace the contents with the following javascript. Included is the Vue resource settings for the X-WP-Nonce WordPress security token in the request header.

main.js
import Vue from 'vue'
import VueResource from 'vue-resource'

import App from './App.vue'

Vue.use(VueResource);

Vue.http.headers.common['X-WP-Nonce'] = wp_api_vuejs_poc.nonce;
Vue.http.options.root = wp_api_vuejs_poc.rest_url;

export default Vue;

new Vue({
    el: '#app',
    render: app => app(App)
});

Build the App

npm run build

Manually refresh the api-test page to verify the build. You should now have a working front end form to Submit a Post.

WordPress api-test Page - Submit Post Form
Submit Post Form

Versions that were used in this tutorial.

  • WordPress 4.7
  • Vue v2.1.0
  • Vue-cli v2.6.0
  • Vue-resource v1.0.3
  • Webpack v2.1.0-beta.25

Source Code

The next page covers using axios, jQuery and other methods for making web requests instead of vue-resource.

Axios

Axios is a popular HTTP client library that covers almost everything vue-resource provides with a similar API.

Install Axios

npm i axios --save-dev

To simplify using Axios in our Vue app, install the vue-axios wrapper for Vue integration.

npm i vue-axios --save-dev

Code Updates

Update src/main.js as follows.

main.js
import Vue from 'vue'

import axios from 'axios'
import VueAxios from 'vue-axios'

import App from './App.vue'

Vue.use(VueAxios, axios)

Vue.axios.defaults.headers.common['X-WP-Nonce'] = wp_api_vuejs_poc.nonce;

export default Vue;

new Vue({
    el: '#app',
    render: app => app(App)
});

Update src/App.vue as follows.

REPLACE

Vue.http.post

WITH

Vue.axios.post

Rebuild the App

npm run build

Uninstall vue-resource

npm uninstall vue-resource --save-dev

Refresh the api-test page and Submit a post to confirm the build and app are working as expected.


The axios-p01 tag in the wp-api-vuejs-poc source code repository on GitHub has been updated to use axios instead of vue-resource for ajax requests:

Source Code

jQuery

Since jQuery is loaded by default in WordPress, we can use its ajax asynchronous HTTP method for the API request.

Code Updates

Remove all of the vue-resource code in src/main.js.

main.js
import Vue from 'vue'

import App from './App.vue'

export default Vue;

new Vue({
    el: '#app',
    render: app => app(App)
});

Replace the script block code in src/App.vue as follows.

import $ from 'jquery'
import Vue from './main.js'

export default {
    data() {
        return {
            post_title: null,
            post_content: null
        }
    },
    methods: {
    onSubmit: function () {

        $.ajax({
            method: "POST",
            url: wp_api_vuejs_poc.rest_url + 'wp/v2/posts',
            data: {
            title: this.post_title,
            content: this.post_content
            },
            beforeSend: function ( xhr ) {
                xhr.setRequestHeader( 'X-WP-Nonce', wp_api_vuejs_poc.nonce );
            },
            success : function( response ) {
                console.log( response );
                alert( wp_api_vuejs_poc.success );
            },
            fail : function( response ) {
                console.log( response );
                alert( wp_api_vuejs_poc.failure );
            }
        });
    }
    },
}

The global jQuery object needs to be available to the app to use its ajax method. Add the externals option to the webpack.config.js and specify jquery so it can be declared as a dependency.

externals: {
    // require("jquery") is external and available
    // on the global var jQuery
    "jquery": "jQuery"
}

The jquery-p01 tag in the wp-api-vuejs-poc source code repository on GitHub has been updated with these changes. The vue-resource plugin is removed and replaced with the ajax method available in the external jQuery library loaded by default in WordPress:

Source Code

Part II

Part 2 of this series covers adding the following to the Vue.js front end WordPress application.

  • List posts submitted by the current user
  • Select from the list to edit a post
  • Delete a post from the list

Resources

comments powered by Disqus