Get started with 33% off your first certification using code: 33OFFNEW

How to Embed a Vue Application within WordPress

2 min read
Published on 6th September 2023

WordPress has been the go-to CMS for many years, powering a significant portion of the web. While WordPress provides a robust and customizable platform, modern web demands have led developers to consider integrating with frontend frameworks like Vue.js. Combining Vue's reactivity with WordPress's backend can lead to dynamic and interactive experiences for users. In this article, we will guide you through embedding a Vue application within a WordPress site.

1. Setting Up Vue

First, set up your Vue application. If you haven't already, install the Vue CLI:

npm install -g @vue/cli

Create a new Vue project:

vue create my-vue-app

2. Building for Production

Once you've developed your Vue app, you need to compile and minify it for production:

cd my-vue-app
npm run build

This command will generate a dist folder containing the compiled assets (JS & CSS files).

3. Uploading Vue Assets to WordPress

  • Navigate to your WordPress installation directory.
  • Create a new directory inside the wp-content/themes directory, e.g., vue-app.
  • Upload the contents of the Vue dist folder to the newly created vue-app directory.

4. Enqueueing Vue Assets in WordPress

To let WordPress know about the Vue assets, enqueue them in your theme's functions.php file:

function load_vue_scripts() {
    // Register and Enqueue Styles
    wp_register_style('vue_style', get_template_directory_uri() . '/vue-app/css/app.css', array(), '1.0.0', 'all');
    wp_enqueue_style('vue_style');

    // Register and Enqueue Scripts
    wp_register_script('vue_script', get_template_directory_uri() . '/vue-app/js/app.js', array(), '1.0.0', true);
    wp_enqueue_script('vue_script');
}
add_action('wp_enqueue_scripts', 'load_vue_scripts');

5. Adding the Vue App within WordPress

Create a new page or post within WordPress. In the content editor, insert a placeholder div for your Vue app:

<div id="app"></div>

Ensure that this ID (app in the example) matches the root element ID specified in your Vue app.

6. Vue Router Considerations

If your Vue app utilizes Vue Router in 'history' mode, you'll have to configure WordPress and your web server to redirect all routes to the Vue app's index.html. Alternatively, you can switch Vue Router to 'hash' mode, which works without additional server configurations.

7. API Requests

For dynamic content from WordPress, you'll likely use WordPress's REST API. Make sure to set up CORS headers if your Vue app and WordPress backend are on different domains.

Embedding a Vue application within WordPress combines the best of both worlds: the flexibility and content management capabilities of WordPress with the interactive and reactive nature of Vue.js. With this setup, you can craft modern, rich user interfaces while leveraging the power of WordPress on the backend.