Build A Single Page App Using Laravel & Vue.js

Please note that this post may contain affiliate links, and for every purchase you make, at no extra cost to you, a commission fee will be rewarded to me.

In the Laravel Tutorial For Beginners and the Django Tutorial For Beginners, we briefly talked about backend development using PHP and Python. And now, we can move onto the front-end and go through the basics of Vue.js, an open-source JavaScript framework.

We start by introducing Vue.js and talk about how to integrate it with Laravel. I choose Laravel as the backend because if you installed the latest version of Laravel, you would notice that it comes with the Vue.js bundle, and in the Laravel documentation, they gave a brief introduction on how to use Vue with Laravel, along with some other tools like Bootstrap and jQuery. If you prefer using Django as your backend, I wrote an article on that as well: Build A Single Page App Using Django & Vue.js

What is Vue.js

Vue.js is an open-source JavaScript framework that follows the model-view-viewmodel architectural pattern. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries or existing projects.

Create A New Laravel App

Let’s start by creating a new Laravel project. Open PhpStorm and create a new project. In this tutorial, I’ll name it “Laravel_Vue”:

Now we need to install Laravel for our project. Open “Terminal”, it should go to the root directory of the project. Run the following commands.

Download the Laravel installer:

composer global require laravel/installer

If you don’t have composer on your computer, you need to install it before running this command.

Create a new Laravel app:

laravel new

This process will take a few minutes to complete.

Download Laravel Installer
Create A New App

Route

To make this tutorial easier, we’ll only create one route and one view as an example. Go to routes/web.php, and add the following code:

Route::get('/', function () {
    return view('vue');
});

Since you are looking to create a Vue app with Laravel as the backend, I assume you already know what this code means. Next, we create a view named vue.blade.php.

View

Go to resources/views, and create a test vue for our project, vue.blade.php:

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel Vue</title>
        
    </head>
    <body>
        <div class="container">
            
        </div>
    </body>
</html>

Inside “container”, we’ll put our Vue component.

Install Bootstrap and Vue Scaffolding

By default, Laravel uses NPM to install all the frontend packages like Bootstrap and Vue.js. The Bootstrap and Vue scaffolding provided by Laravel is located in the laravel/ui Composer package, which may be installed using Composer:

composer require laravel/ui

Once the laravel/ui package has been installed, you may install the frontend scaffolding using the ui Artisan command:

php artisan ui bootstrap
php artisan ui vue

Before we start writing Vue components, we need to install JavaScript dependencies. All JS dependencies required by our app can be found in the package.json file. It is similar to the composer.json file, except it specifies the JavaScript dependencies instead of PHP.

The following command will help you install these dependencies for our project. But remember, you need to install npm on your computer if you haven’t done that.

npm install

Once the package is installed, you can run the npm run dev command to compile your assets. Or you can run the following command, which will be constantly monitoring your files, once it changes, it will be recompiled:

npm run watch

After using laravel/ui package to scaffold your frontend, you should notice that an example Vue component has been generated in the resources/js/components directory. The ExampleComponent.vue is an example of a single file Vue component, which defines its HTML and JavaScript template in the same file.

A typical Vue component has three sections: template, script, and style. The template part contains HTML code, which defines the content of the Vue component. The style part is where you put CSS code, it determines how the content looks. And finally, the script section has all the JavaScript code for your app.

Use Vue Component In Blade Template

First, let’s take a look at the resources/js/app.js file, this is the entry point of our Vue components. Every time we create a Vue component, we need to register it here:

/**
 * First we will load all of this project's JavaScript dependencies which
 * includes Vue and other libraries. It is a great starting point when
 * building robust, powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * The following block of code may be used to automatically register your
 * Vue components. It will recursively scan this directory for the Vue
 * components and automatically register them with their "basename".
 *
 * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
 */

// const files = require.context('./', true, /\.vue$/i)
// files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default))

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

/**
 * Next, we will create a fresh Vue application instance and attach it to
 * the page. Then, you may begin adding components to this application
 * or customize the JavaScript scaffolding to fit your unique needs.
 */

const app = new Vue({
    el: '#app',
});

Line 22 registers the example component. The first parameter determines the name of the HTML tag that we will use in the blade template. The second parameter sets the Vue component that we need to register. If you have multiple components, you need to register all of them here.

To use this example component, we need to drop it into the Laravel blade template we just created like this:

<div class="container">
    <example-component></example-component>
</div>

Now, start the development server, compile the frontend assets, open the browser, and go to http://127.0.0.1:8000/. You should be able to see the example component.

If you are new to Vue.js and JavaScript, I wouldn’t suggest you start by reading the official documentation, because it is not designed for beginners. Personally, I prefer learning by building some small projects, which is why in the next article, we’ll build a simple unit converter, and in the process, we can familiarize ourselves with Vue file structure and template syntax.

Leave a Reply

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