Articles

How to use Laravel with Vue.js 3

Vue.js is one of the most used JavaScript framevorks for creating web interfaces and single page applications, together with Laravel it becomes a very powerful development tool.

For the development of web apps, a widely used tool is vuejs, and in this article we will see how to install and use it with Laravel. The Vue.js framework was definito progressive framework because it is specialized in the creation of HTML views, and allows you to easily integrate with components of other libraries and projects.

The success of Vue.js is also due to the choice of Laravel to suggest it as a frontend framework, thus leading to the release of version 2.0.

Laravel project creation

The first step is, of course, to create a new project in Laravel. If you have one on your computer, use it or you can create a new one just for this tutorial.

composer create-project laravel/laravel guide-laravel-vue

After the project has started, you will need to install the npm addictions. To do this, run the following command inside your project directory:

npm install

Once the dependencies are installed, run the following command to build the resources and make sure everything really works:

npm run dev

The command npm run dev performs a variety of checks and builds, in particular Laravel Mix compile the file resources/js/app.js and the file resources/css/app.css in files public/js/app.js e public/css/app.css.

When finished if everything works fine, you will see something like this:

Installing Vue.js

After preparing the Laravel project, we can proceed to install Vue.js 3. To do this, run the following command in your project directory:

npm install --save-dev vue

This will install Vue.js as one of the development dependencies. After compiling the assets, your production JavaScript file will be self-contained, so you just need to install Vue.js as a development dependency.

To make sure Vue 3 was installed correctly, open the file package.json (present in project root) and search for "vue" in the section "devDependencies":

// package.json

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "mix",
        "watch": "mix watch",
        "watch-poll": "mix watch -- --watch-options-poll=1000",
        "hot": "mix watch --hot",
        "prod": "npm run production",
        "production": "mix --production"
    },
    "devDependencies": {
        "axios": "^0.21",
        "laravel-mix": "^6.0.6",
        "lodash": "^4.17.19",
        "postcss": "^8.1.14",
        "vue": "^3.2.37"
    }
}

As you can see, the version number indicates that Vue.js 3 has been installed. 

First try of Vue.js

In your welcome.blade.php file put the following code:

<div id="vue-app">
    {{ text }}
</div>
<script>
window.vueApp = new Vue({
  el: '#vue-app',
  data: {
    text: 'Hello World from Vue!'
  }
});
</script>

As you can see we have created an element div with id "vue-app“. Inside the script element we have created an instance of Vue, where we pass to the constructor an object that allows us to definish some application parameters, such as data and behaviors, in our case:

  • el: Reference to the element div defifinished in the html
  • date: dataset

As soon as the object is created, Vue acquires the div with id vue-app and takes care of replacing the placeholder {{ text }} with the value contained within the data object. Of course, this object can contain more than one property, even of different types: numbers, arrays and other nested objects are valid

Innovation newsletter
Don't miss the most important news on innovation. Sign up to receive them by email.

Besides this replacement, Vue has also activated its engine and made the application responsive, i.e. any change to the text property will cause an instant update of the corresponding element in the HTML.

Second test of Vue.js

To proceed to the second trial, you'll first need to instantiate the app to create a new component. You open resources/app.js (o resources/js/app.js) and update its content as follows:

// resources/app.js

require('./bootstrap');

import { createApp } from 'vue';
import HelloVue from '../components/HelloVue.vue';

createApp({
    components: {
        HelloVue,
    }
}).mount('#app');

In this file we are creating a new Vue.js instance, and to do this we need a Vue component which we have called HelloVue.vue. For more information consult the official documents . 

Create a new file resources/components/HelloVue.vue and enter the following code:

// resources/components/HelloVue.vue

<template>
  <h1>Hello Vue!</h1>
</template>

<script>
export default {
    name: 'HelloVue'
}
</script>

The file we just created is a basic Vue.js component that prints Hello Vue! like header1 on the page. Finally, open the webpack.mix.js file in the project root and update its contents as follows:

// webpack.mix.js

const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
    .vue({
        version: 3,
    })
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]);

In this file, the method call .vue() will compile any Vue.js code and bundle it into the production JavaScript file. The function accepts an object where you can definish the version of Vue.js you are using. 

After editing the file webpack.mix.js you need to compile the javascript code. To do this, we run the command again npm run dev.

Finally, to try Vue operationally, open the file resources/views/welcome.blade.php and enter the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Laravel Vue</title>
    <script src="{{ asset('js/app.js') }}" defer></script>
</head>
<body>
    <div id="app">
        <hello-vue />
    </div>
</body>
</html>

The code, together with the previously created component, will produce a video message Hello Vue!, due to the Vue.js instance being mounted on an HTML element with id app.

Run your application using php artisan serve, and open it in your favorite browser.

Ercole Palmeri

You might also be interested in ...

Innovation newsletter
Don't miss the most important news on innovation. Sign up to receive them by email.

Latest Articles

The Future is Here: How the Shipping Industry is Revolutionizing the Global Economy

The naval sector is a true global economic power, which has navigated towards a 150 billion market...

May 1, 2024

Publishers and OpenAI sign agreements to regulate the flow of information processed by Artificial Intelligence

Last Monday, the Financial Times announced a deal with OpenAI. FT licenses its world-class journalism…

April 30 2024

Online Payments: Here's How Streaming Services Make You Pay Forever

Millions of people pay for streaming services, paying monthly subscription fees. It is common opinion that you…

April 29 2024

Veeam features the most comprehensive support for ransomware, from protection to response and recovery

Coveware by Veeam will continue to provide cyber extortion incident response services. Coveware will offer forensics and remediation capabilities…

April 23 2024