Starting Out With VueJS
Today we are going to take a look at a brilliant JavaScript library that allows you to quickly create a View layer for your application. It is easy to work with and exceptionally fast. That doesn’t mean it can only be used for your View layer though, there are components out there such as vue-router
that add features that easily allow it to compete with other popular JavaScript libraries such as Angular or React.
This tutorial is going to be a very simple one looking at how to get started with Vue. We will be using a static data set (not pulling from an API or external source), and creating a horrible looking but very simple take on a ToDo system. I say horrible looking because I’m awful at design, but who cares. You’re here to learn how to use Vue, not make things pretty… Right?
Fleshing Out
First up, we want to get a basic page up and running. Let’s make a basic HTML page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link type="text/css" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> </head> <body> <!--[if lt IE 7]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.15/vue.min.js"></script> </body> </html> |
There we have a simple modern HTML skeleton with jQuery, Bootstrap (you can add JS if you want) and Vue. Load it up (via a localhost like XAMPP or Vagrant please, not file) and you should have bupkis, but that’s to be expected.
Basic Layout
Now I’m sick of all the normal ToDo apps that everyone makes, but they serve a good basis for learning things. So to mix it up, let’s make a Film Watch list. It has the same principle ideas as a ToDo list, just it’s a list of films I have or haven’t watched yet. So let’s add in the HTML for our Film Watch list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<div class="container"> <div class="col-md-12"> <h1 class="text-center">Film List</h1> </div> </div> <div class="container"> <div class="col-md-12"> <table class="table"> <thead> <tr> <th>Title</th> <th>Watched</th> </tr> </thead> <tbody> <tr> <td>The Movie Title</td> <td> <input type="checkbox" name="watched" /> </td> </tr> </tbody> </table> </div> </div> |
With that you should have something that displays a single film in a basic Bootstrap style table.
Not super exciting I know, but what if we could get it listing from a list of data and get some interactivity slipped in there? Well first let’s head toward getting it reading from a list of data instead of it being hard coded.
Adding Local Data
Before we get to adding in the data we need to instantiate Vue and tell it where our application code is. We will be adding our code to our HTML page (via a script tag) to keep things all in one place, but I strongly advise putting it into a separate JS file whenever possible.
1 2 3 |
new Vue({ el: '#app' }); |
Now you just need to add the ID app
to the element that will contain your application. I strongly advise using an element other than the body tag as it means you have the option of placing other code outside of your Vue application, it also reduces the need for Vue to parse anything that will not have anything to do with your application code. In our case I have used the second div
element with the class container
as that will contain our application.
Now we can finally add our data.
1 2 3 4 5 6 7 8 9 10 |
new Vue({ el: '#app', data: { movies: [ { title: 'The Boy', watched: false }, { title: 'Avengers: Age of Ultron', watched: true } ... ] } }); |
This is just a simple JavaScript array of objects. The only thing to note is the data
property of the Vue instance. This is where any data you wish Vue to include in data binding must be placed. Data binding is another way of saying that when the data is changed Vue will update anything that uses said data to reflect the new value.
Of course adding this code will not magically make it appear in the code. To do that we need to add some Vue magic to our HTML, so let’s do that now.
Adding Vue Attributes
Vue takes a leaf out of Angular’s book and allows us to add special attributes into our HTML to tell Vue what we want to do with certain elements. Remember though that they will only be recognized inside the element we added the ID to. Instead of going through adding each attribute, here is the full modified code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<div class="container" id="app"> <div class="col-md-12"> <table v-if="movies" class="table"> <thead> <tr> <th>Title</th> <th>Watched</th> </tr> </thead> <tbody> <tr v-for="movie in movies"> <td><span v-if="!movie.watched">{{ movie.title }}</span><del v-if="movie.watched">{{ movie.title }}</del></td> <td> <input type="checkbox" name="watched" v-model="movie.watched" /> </td> </tr> </tbody> </table> </div> </div> |
First thing to note, before we look at the attributes we have added, is the mustaches (curly braces). If you are familiar with templating languages such as Mustache, Twig or Laravel’s Blade, you will instantly know that these are used for surrounding variables to be parsed. Well that applies here too. The difference is that all interpolated (AKA parsed) variables are data bound and will be updated automagically when the data changes. There are ways to make unbound interpolations but you can read more about that in the Vue data binding documentation.
Let’s take a look at each of the attributes we’ve added. All the attributes starting with v-
are Vue related. We will be going in the order they appear in the code from top to bottom.
v-if
Does exactly what you would think it does. It will only display the element and its contents if the variable exists & is a truthy value of some kind. So true
, 1
, an array, an object, these are all truthy values. It is important to note that the point of reference (or scope, if you will) is the data
property of the Vue instance, however you can do simple expressions (4 + 4 > 7
) and they will be evaluated and the result used to determine the outcome of the conditional.
v-for
This does exactly what it does in most programming languages. It will loop through each item in the array given. It works by using the format item in items
where item
is the variable that the single item will be assigned to and items
is the original variable containing the array.
While inside the element the v-for
is applied to you will have access to the single item and a special variable called $index
which contains the index of the item the array pointer is currently at. Remember this number starts from zero as it is an array index, not a counter.
v-model
This is the magical one. This attribute tells Vue to create a two-way data binding to the form element (input) and the variable given. That means when the value of the checkbox is changed the value of (in this case) movie.watched
will also be changed to match. The same applies the opposite way around. If you were to use the console to update the value it would automatically check or uncheck the checkbox as needed.
The magic is in the fact that v-model
automatically detects the form element type and changes the binding type to match. So it works on text fields, checkboxes, radios and selects without any changes needed.
Vue in Action
Now the scary thing is that is it. If you load your page you should have a working Film Watch list. Try clicking the checkboxes and you’ll see things update. The functionality works as it should and you have successfully used Vue to create something. It is very basic at the moment, but I didn’t want to over-complicate things to start out with.
You can now check out the second part of the Starting Out With Vue tutorial.