Creating WordPress plugin front end with Vue

This is a short instruction how to set up Vue based front-end for your WordPress Plugin. We will be using the generated in WordPress Dashboard.

Begin with creating Vue project with Vue CLI as instructed in Vue documentation. Then create separate project for WordPress plugin. In the plugin main php file add action for admin menu that loads Javascript only when the menu page is opened:

<?php
add_action('admin_menu', 'makePeachesAdminMenuPage');

function makePeachesAdminMenuPage() {
	$page_hook_suffix = add_menu_page(
		'MangoFP Plugin Page',
		'MangoFP',
		'manage_options',
		'mangofp-admin',
		'renderAdmin'
	);
	add_action( "load-{$page_hook_suffix}", 'loadAdminJs' );
}

function loadAdminJs() {
    add_action('admin_enqueue_scripts', 'initAdminPage');
}

function initAdminPage() {
    registerVueScripts();
    // more to follow here 
}



Function registerVueScripts does the actual work.

<?php
function isDebug() {
    return ( defined('MANGO_FP_DEBUG') && MANGO_FP_DEBUG );
}

function registerVueScripts() {
	$chunk_vendors_js = plugin_dir_url( __FILE__ ) . 'assets/js/chunk-vendors.js';
    $app_js = plugin_dir_url( __FILE__ ) . 'assets/js/app.js';
    if (isDebug()) {
        $chunk_vendors_js = 'http://localhost:8080/js/chunk-vendors.js';
        $app_js = 'http://localhost:8080/js/app.js';
    }
    wp_register_script(
		'vue_vendors',
		$chunk_vendors_js,
		false, //no dependencies
		'0.0.1',
		true //in the footer otherwise Vue triggers it too early
	);
	wp_register_script(
		'vuejs',
		$app_js,
		['vue_vendors'],
		'0.0.1',
		true //in the footer otherwise Vue triggers it too early
	);

	wp_enqueue_script('vue_vendors');
	wp_enqueue_script('vuejs');

    if (!isDebug()) {
        wp_register_style( 'vue-vendor-styles',  plugin_dir_url( __FILE__ ) . 'assets/css/chunk-vendors.css' );
        wp_enqueue_style( 'vue-vendor-styles' );
        wp_register_style( 'vue-app-styles',  plugin_dir_url( __FILE__ ) . 'assets/css/app.css' );
        wp_enqueue_style( 'vue-app-styles' );
    }

}

isDebug function here is used to select between development and production versions of front end code. Using the development version of Javascript and CSS files works only if they are served from local computer (npm run serve) with Vue default settings. To declare for WordPress, that this is your plugin’s development environment add to the wp-config.php:

<?php
// Set to true for local MAangoFp plugin development in order to run against locally served frontend development server
define( 'MANGO_FP_DEBUG', true );
Comments are closed.