Introduction to vue.js in Laravel

Avinash Nethala
justlaravel
Published in
6 min readApr 26, 2017

Hello everyone! Welcome to justlaravel.com. Here I am going to discuss on vue.js and how to use Vue js in your laravel applications. ‘Vue — The Progressive JavaScript Framework’ is used for building user interfaces. As with laravel 5.3 onwards, it suggests us to use Vue as a default javascript framework. So here I will show you how to get started with Vue.

Here I made a simple application, where we can insert some data to database and show that data in the front end, I have made such applications before, some of them are ajax CRUD operations, bootgrid plugin, datatables plugin and some others, in all these applications I used the laravel way to call the controllers return data to view from them or in ajax case, I used some ajax calls. In this app I will tell you how to do the same things the VUE way.

Setup Vue

Laravel uses npm to install all the related dependencies like vue, bootstrap, etc. Run the following command,

npm install

Make sure you have the latest node and npm versions as some packages like laravel-mix require highest versions of node and npm.

So after installing all the necessary packages, you can see a directory named ‘node-modules’ in your applications root directory.

You can see a file named app.js in /resources/assets/js/ directory of your app. I am going to write all the vue in this file itself.

Overview of the application:

Here it has one text field to enter some text and a button to add that to the database. In the same page it shows all the entries in database with an option to delete any item. All the front end operations here like showing the items, and updating the page when new item is added, deleting an item is all managed by vue.js

Intro to vue.js - justlaravel.com
Intro to vue.js — justlaravel.com

Input Form:

Here the app has one input field and one button.

<div class="form-group row">
<div class="col-md-8">
<input type="text" class="form-control" id="name" name="name"
v-model="newItem.name" placeholder=" Enter some name" required>
<p class="error text-center alert alert-danger hidden"></p>
</div>
<div class="col-md-4">
<button class="btn btn-primary" @click.prevent="createItem()"
id="name" name="name">
<span class="glyphicon glyphicon-plus"></span> ADD
</button>
</div>
</div>

In the above snippet, for button I used @click.prevent="createItem()" which calls createItem vue method which is declared in /resources/assets/js/app.js file.

Reading/Displaying the data

A simple table is used to display the data,

<div class="table table-borderless" id="table">
<table class="table table-borderless" id="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Actions</th>
</tr>
</thead>
<tr v-for="item in items">
<td>@{{ item.id }}</td>
<td>@{{ item.name }}</td>
<td>Delete Button</td>
</tr>
</table>
</div>

Here I used the v-for directive to render the list of items and display all the items in our table.

The syntax here item in items is the vue syntax for v-for directive. The items contains all the data and I just get each value using item So basically our app just has one item, so I will just show item and its id along with the delete option.

I wrapped all this HTML in a div called vue-wrapper, as Vue needs an element scope to reflect the changes on it.

However, I get all the items from the js which is declared in /resources/assets/js/app.js file.

The VUE part

Open the app.js in /resources/assets/js/ directory of your app.

First I will just tell the vue, which element to be affected,

const app = new Vue({
el: '#vue-wrapper',

I also need to set the data in the vue,

data: {
items: [],
hasError: true,
hasDeleted: true,
newItem : {'name':''}
},

Here the array items contains all the items, and newItem contains the structure of the data in each item, here I store only name, If you wish you can add as many as you want newItem : {'name':'','id':'','age':''}.Also for error handling I used hasError and hasDeleted which shows an error when empty value is submitted and a success message when an item is deleted respectively.

Now I will write some vue methods for creating a new item, deleting an item and showing all the items.

methods : {
getVueItems: function(){
},
createItem: function(){
},
deleteItem: function(){
};
},

I will now discuss each method,

getVueItems

Here I will show all the items in the database, and display them in our page. For back end operation we use laravel itself. Getting data is as usual as I done in many of my previous posts, but here I will call that function from vue itself. axios.get('/vueitems') calls the vueitems URI, which is defined in the app routes file routes/web.php

Route::get ( '/vueitems', 'MainController@readItems' );

This readItems function in our controller,

public function readItems() {
$data = Data::all ();
return $data;
}

That function simply fetches all the items in the database and returns the data, which will be handled in vue.

So now let’s see the complete getVueItems method.

getVueItems: function(){
axios.get('/vueitems').then(response => {
this.items = response.data;
});
}

Here the data which we got from controller is been set to the items array as you can see this.items = response.data; does it for us.

Now in the view file resources/views/welcome.blade.php I used a vue loop to display this data.

<tr v-for="item in items">
<td>@{{ item.id }}</td>
<td>@{{ item.name }}</td>
</tr>

createItem

A new item is created when we click on the add button, which is discussed above. As you see the @click.prevent="createItem()" calls the createitem method.

First I will get the input and check if it is empty and show some error if it is empty else add that item to database and also update the view.

Here I set some errors and success messages in the view and handle its visibility in the js.

for empty value,

<p class="text-center alert alert-danger" 
v-bind:class="{ hidden: hasError }">Please enter some value!</p>
Intro to vue.js - justlaravel.com
Intro to vue.js — justlaravel.com

for success message,

<p class="text-center alert alert-success" 
v-bind:class="{ hidden: hasDeleted }">Deleted Successfully!</p>
Intro to vue.js - justlaravel.com
Intro to vue.js — justlaravel.com

Here I used vue bind feature which allows me to add or remove a class. I need it here because I only want to show those messages when an error in user input or an item is deleted. i don’t want them to be displayed all the time. So I just write them and initially set their visibility to hidden. Later I will remove its class when needed. In such cases v-bind feature comes handy.

createItem: function(){
var input = this.newItem;
if(input['name'] == ''){
this.hasError = false;
this.hasDeleted = true;
}
else{
this.hasError = true;
axios.post('/vueitems',input)
.then(response => {
this.newItem = {'name':''};
this.getVueItems();
});
this.hasDeleted = true;
}
}

So initially check for empty value and if the value is empty, I will show the message, to show the error message, I need to remove the class : hidden on that message. So I set that hasError flag to false and at this point I need to hide all other messages as well so will also hide success message for delete too.

If a valid input is given I will store them in the database and update the view. For back end saving operation I use normal laravel way of saving.

Route::post ( '/vueitems', 'MainController@storeItem' );

The storeItem method,

public function storeItem(Request $request) {
$data = new Data ();
$data->name = $request->name;
$data->save ();
return $data;
}

The above snippet just gets the value from the form and saves it in the database. In the above vue method at the end I call getVueItems which will update the view with the latest change.

deleteItem

While displaying all the items, I also kept a button to delete the item, when clicked it calls deleteItem(item) vue method.

<td @click.prevent="deleteItem(item)" class="btn btn-danger"><span
class="glyphicon glyphicon-trash"></span></td>

the vue method,

deleteItem: function(item){
axios.post('/vueitems/'+item.id).then((response) => {
this.getVueItems();
this.hasError = true,
this.hasDeleted = false
});

The controller method for delete,

public function deleteItem(Request $request) {
$data = Data::find ( $request->id )->delete ();
}

The above function deletes the item with respect to the id sent from the Vue call. Again in the Vue method, I set the delete message to visible by turning off the flag hasDeleted

That’s it guys, we have done with our first Vue application in laravel.

--

--