Vue.js shares similar concepts to other popular JavaScript frameworks like Rivet.js, Ractive.js, Angular.js, and Knockout.js. These types of frameworks offer a structural outline for interactive web applications. Raw HTML acts as the templating language, while these frameworks extend the syntax to provide data binding and User Interface data modeling. Vue.js strives to make working with these types of frameworks as simple and functional as possible. Let’s go through a Vue.js tutorial to learn about how it works, and what it can offer us.

# Creating a Vue Instance

Before we can do anything with Vue, we need to instantiate a new Vue instance, or View Model, which corresponds to a specific containing element in the dom. We already have a containing div, so we will assign that div the id of #myvueinstance , and use a css selector in the Vue instance to bind the two together.

html

1 2 3 4 5 <div id = "myvueinstance" class = "container" > <!-- build out all kinds of things here --> </div>

js

1 2 3 var viewmodel = new Vue ( { el : '#myvueinstance' } ) ;

Congratulations! You have created your first Vue instance. What this means is that this div with the id of #myvueinstance , as well as any other elements it contains, now has access to all of the magic that your Vue instance can provide. This div is now Vueified if you will.

# Vue.js Two Way Data Binding

We now have a div that has the magical powers of Vue bound to it. We are free to start building out some elements within this parent now. To demonstrate the two way binding feature, we will use a text input with the v-model directive. Think of these directives as simply another attribute of html. In fact, we are extending html in a way by using these directives. Directives are a key part of VueJS.

html

1 2 3 4 5 6 7 8 9 <div id = "myvueinstance" class = "container" > <div class = "row" > UI element </div> <input type = "text" v-model = "textinput" class = "form-control" > <p> </p> <div class = "row" > Vue Instance data object </div> {{ $data | json }} </div>

js

1 2 3 4 5 6 7 var viewmodel = new Vue ( { el : '#myvueinstance' , data : { textinput : 'Too hot, hot damn.' } } ) ;

Try it! Type “living it up in the city” in the text box.

As you can see, the data is updated in real time in both directions.

# Displaying Lists with Vue.js

How can we loop through an array of data and output each item one at a time in Vue.js? Well, just like PHP has a foreach construct, and JavaScript has a for(in), Vue.js uses the v-for directive to easily loop over data, and take action on it. It’s so simple, it’s almost deceiving at first. First, we’ll set up an array of JavaScript libraries to work with in our Vue Instance.

js

1 2 3 4 5 6 7 var viewmodel = new Vue ( { el : '#myvueinstance' , data : { libraries : [ 'angular.js' , 'd3' , 'node' , 'jquery' ] } } ) ;

Now we will tie in to that data in our html.

html

1 2 3 <ul class = "nav nav-pills" > <li v-for = "library in libraries" class = "active" > <a href = "#" > {{ library }} </a> </li> </ul>

note: Pay attention to the syntax we are using with the v-for directive. When working with loops, you might be used to making sure you keep your singulars and plurals in order so you can more easily reference the desired element on each iteration of the loop. In PHP, it follows the notion of foreach (plural as singular) and in JavaScript it follows something like for (singular in plural).

<li v-for=”library in libraries” class=”active”><a href=”#”>{{ library }}</a></li>

I like to read this snippet as follows: For each library in libraries, echo out one library one at a time. In fact, this snippet does give us the desired result as you can see here.

UI List Element angular.js

d3

node

jquery

Like everything in programming, there are many more ways to do the same thing we just did here. In the efforts of brevity, we’ll move forward for now. Do check out the official docs if you are a “need to know everything” type of person. 🙂

Add More Libraries to our Libraries array.

It might be nice to be able to add items to our array, and have the user interface update in real time. In addition, we want the text field to clear as soon as we add a new item. Once this is in place, we also want a button to delete all libraries. We can do this.

js

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 var viewmodel = new Vue ( { el : '#myvueinstance' , data : { libraries : [ 'angular.js' , 'd3' , 'node' , 'jquery' ] , newlibrary : '' } , methods : { addLibrary : function ( ) { this . libraries . push ( this . newlibrary ) ; this . newlibrary = '' ; } , deleteLibraries : function ( ) { this . libraries = [ ] ; } } } ) ;

html

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <div id = "myvueinstance" class = "container" > <div class = "row" > UI List Element </div> <ul class = "nav nav-pills" > <li v-for = "library in libraries" class = "active" > <a href = "#" > {{ library }} </a> </li> </ul> <p> </p> <input class = "form-control" type = "text" placeholder = "Type the library name here, then click the button below." v-model = "newlibrary" > <button class = "btn btn-info" v - on : click = "addLibrary" > Click to add library </button> <button class = "btn btn-danger" v - on : click = "deleteLibraries" > Click to delete all libraries </button> <p> </p> <div class = "row" > Vue Instance data object </div> {{ $data | json }} </div>

Try it! Type “Vue.js” in the text box, then click the button.

# The Vue.js Event System

Back in the day, we used to have to do things like this <div id=”element” onclick=”alert(‘you just clicked this’);”></div> with native JavasScript. We then moved onto more advanced ways of interacting with events using jQuery in a manner more like this $(“#element”).click(function() { alert(“you just clicked this”); });. To be honest, it has been confusing to deal with over time as the best practices have changed more than the wind direction. Vue.js stops this nonsense and makes working with events ridiculously easy. In fact, we’ve already been using events with Vuejs in this tutorial, but let’s just quickly review them now. All you need to do to add an event listener to an element is use the v-on directive in combination with the type of event you would like to use. It takes the format of:

v-on:event=”function”

event can be any of the standard JavaScript events like onfocus, onblur, onchange, onselect, onmouseover, onclick, onload, onsubmit, etc but, minus the ‘on’ portion! The equivalent in Vue would be something like v-on:focus=”function”, v-on:blur=”function”, v-on:change=”function”, v-on:select=”function”, v-on:mouseover=”function”, v-on:click=”function”, v-on:load=”function”, v-on:submit=”function”.

Once you decide which event you want to respond to, you think of a custom function name that gets passed to it. This is what comes as the attribute name in v-on:event=”function” This custom named function then gets declared in the methods object of the Vue instance. So just to tie this together, instead of one of these first two:

native js

1 <div id = "element" onclick = "alert(‘you just clicked this’);" > </div>

jquery

1 2 3 $ ( "#element" ) . click ( function ( ) { alert ( "you just clicked this" ) ; } ) ;

All you need to do with Vue is this!

html

1 <div id = "element" v - on : click = "myfunction" > </div>

Vue js

1 2 3 4 5 methods : { myfunction : function ( ) { alert ( 'you just clicked this' ) ; } }

If you follow this general outline, you’ll find you can implement any type of event listener and associated handlers in a clean and simple way with Vuejs.

# Filtering with Vue.js

What is a filter in Vue.js? The Vue.js website explains filters as follows:

A Vue.js filter is essentially a function that takes a value, processes it, and then returns the processed value. In the markup it is denoted by a single pipe (|) and can be followed by one or more arguments

Filters are functions that receive a value, filter them as needed, and then output the result onto the web page. There are many built in filters right in the Vue framework itself that cover many common use cases such as capitalize, uppercase, lowercase, currency, pluralize, json, key, filterBy, and orderBy. The following example will show a basic use case for filterBy and orderBy.

We’ll create an array of objects where each object has an id and framework property. We can fill the id properties with numerical values, and the framework property with the names of some common JavaScript libraries. This frameworks array will serve as the basis for testing out Vue’s built in filterBy and orderBy filters.

html

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <div id = "myvueinstance" class = "container" > <div class = "row" > UI List Element </div> <input type = "text" class = "form-control" v-model = "filterkey" > <table class = "table table-hover" > <thead> <tr> <th> <a href = "#" v - on : click = "sortvia('id')" > id </a> </th> <th> <a href = "#" v - on : click = "sortvia('framework')" > framework </a> </th> </tr> </thead> <tbody> <tr v-for = "framework in frameworks | filterBy filterkey | orderBy sortparam order" > <td> {{ framework.id }} </td> <td> {{ framework.framework }} </td> </tr> </tbody> </table> </div>

js

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 27 28 29 30 31 32 33 34 35 36 37 var viewmodel = new Vue ( { el : '#myvueinstance' , data : { sortparam : '' , fitlerkey : '' , order : 1 , frameworks : [ { id : '001' , framework : 'angular' } , { id : '002' , framework : 'd3' } , { id : '003' , framework : 'node' } , { id : '004' , framework : 'jquery' } , { id : '005' , framework : 'reveal.js' } , { id : '006' , framework : 'impress.js' } , { id : '007' , framework : 'backbone.js' } , { id : '008' , framework : 'meteor.js' } , { id : '009' , framework : 'express' } , { id : '010' , framework : 'moment' } , { id : '011' , framework : 'underscore' } , { id : '012' , framework : 'gulp' } , { id : '013' , framework : 'react' } , { id : '014' , framework : 'ghost' } , { id : '015' , framework : 'sweetalert' } , { id : '016' , framework : 'select2' } , ] } , methods : { sortvia : function ( sortparam , order ) { this . order = this . order * - 1 ; this . sortparam = sortparam ; } } } ) ;

Try it! Click id or Framework to sort by that column. Enter a search in the text field to filter.

# Vue.js Custom Filters

The built in filters for Vue.js will take you a long way in meeting many common use cases. In addition to the filters that ship with the framework, you can also create your very own custom filters both on a per Vue instance, or via a global instance.

Vue filters per instance

First off we’ll take a look at how we can set up a custom filter on a per instance type of scenario. This is where you would define the function within the filters object of the Vue instance.

html

1 2 3 4 5 6 7 <div id = "myvueinstance" class = "container" > <h4> {{ string | upper }} </h4> <h4> {{ string | lower }} </h4> </div>

In the snippet above, we output a string two times. The first time, we pipe it to an upper filter. The second time, we pipe it to a lower filter. Let’s see how we created these in our JavaScript.

js

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 var viewmodel = new Vue ( { el : '#myvueinstance' , data : { string : 'Custom Filters' } , filters : { upper : function ( value ) { return value . toUpperCase ( ) ; } , lower : function ( value ) { return value . toLowerCase ( ) ; } } } ) ;

Upon running this in the browser, we see both instances work great as CUSTOM FILTERS and custom filters is output to the screen.

Global Vue filters

We can create more than one Vue instance when working with our code. Consider that we have another div in our html, and another Vue instance in our JavaScript. We will again populate the string property with some text, and we will try to apply our filters we already created to them.

html

1 2 3 4 5 6 7 <div id = "anotherdiv" class = "container" > <h4> {{ string | upper }} </h4> <h4> {{ string | lower }} </h4> </div>

js

1 2 3 4 5 6 7 var anothermodel = new Vue ( { el : '#anotherdiv' , data : { string : 'Spooky action from a distance.' } } ) ;

At this point, our browser is outputting the following:

1 2 3 4 CUSTOM FILTERS custom filters Spooky action from a distance . Spooky action from a distance .

See how the first two lines are being operated on by the upper and lower filters? Notice that lines three and four are simply outputting the string as if they have ignored the upper and lower filters. In fact, they are ignoring those filters because they are bound to the first Vue instance and not the second. How can we use those filters on both instances? We can get our spooky action at a distance by making them global of course! Let’s change up our JavaScript to this:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Vue . filter ( 'upper' , function ( value ) { return value . toUpperCase ( ) ; } ) ; Vue . filter ( 'lower' , function ( value ) { return value . toLowerCase ( ) ; } ) ; var viewmodel = new Vue ( { el : '#myvueinstance' , data : { string : 'Custom Filters' } } ) ; var anothermodel = new Vue ( { el : '#anotherdiv' , data : { string : 'Spooky action from a distance.' } } ) ;

By making our upper and lower filters global, and removing them from the filters object of the first instance, we can now make use of them on any Vue instance in our html. Reloading our browser shows that this is in fact the case.

1 2 3 4 CUSTOM FILTERS custom filters SPOOKY ACTION FROM A DISTANCE . spooky action from a distance .

Those are the basics of filters in Vue.js, but do go ahead and hit up the filters documentation for more features like two way filters and dynamic arguments.

# Vue.js Components

Components are a really slick way of creating your own html elements for reuse. That is to say, you can define a custom html tag, and implement what that tag does in Vue.js for you. As an example, let’s try to make an <alert> tag we can use.

js

1 2 3 4 5 6 7 Vue . component ( 'alert' , { template : '<div class="alert alert-success" role="alert"><b>Smashing!</b> Nice work.</div>' } ) ; var viewmodel = new Vue ( { el : '#myvueinstance' } ) ;

html

1 2 3 4 5 <div id = "myvueinstance" class = "container" > <alert> </alert> </div>

With just this small snippet of code, we now have a reusable alert tag, as you can see here.

Smashing! Nice work.

Wow. I’m sure you can see the power there. Imagine the things you could do with this!

# Vue.js Component Props

If you’re excited with what your own components can do for you, you’re about to jump for joy when you see what component props can do for you! In the example above, we created our very own tag, and we can use it anywhere we might need to produce an alert. At the moment, it is hard coded so to speak. What about different alert types, with different messages? How can we do this? I give you: Props!

js

1 2 3 4 5 6 7 8 9 10 Vue . component ( 'alert' , { props : [ 'type' , 'bold' , 'msg' ] , template : '<div class="alert alert-{{ type }}" role="alert"><b>{{ bold }}</b> {{ msg }}</div>' } ) ; var viewmodel = new Vue ( { el : '#myvueinstance' } ) ;

html

1 2 3 4 5 6 7 8 <div id = "myvueinstance" class = "container" > <alert type = "info" bold = "Greetings." msg = "This is some information." > </alert> <alert type = "warning" bold = "Slow down." msg = "You might crash." > </alert> <alert type = "danger" bold = "Oh no!" msg = "The program just crashed!" > </alert> <alert type = "success" bold = "Rock Out" msg = "with your Props out!" > </alert> </div>

Note that the props property holds an array of strings. Those strings become attributes on your custom html element. You then simply provide whatever you want to those attributes in your html, and witness the magic happen.

Greetings. This is some information.

Slow down. You might crash.

Oh no! The program just crashed!

Rock Out with your Props out!

Cool! With a good dose of imagination, you could create some really amazing components for use in any of your projects.

# Custom Directives with Vue.js

As we have learned, directives in Vue.js are the custom attributes that begin with v- in the html markup. In addition to all of the standard directives that perform various operations, you can use Vue.js to create custom directives. By creating custom directives you can, in a sense, program Vue to map data changes to dom behavior according to your liking.

As an example, we will create a new v-twitter custom directive, that when clicked, will open a window to share an article on twitter.

js

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Vue . directive ( 'twitter' , function ( message ) { this . el . addEventListener ( 'click' , function ( ) { var width = 818 , height = 400 , left = ( document . documentElement . clientWidth - width ) / 2 , top = ( document . documentElement . clientHeight - height ) / 2 , url = 'https://twitter.com/intent/tweet?text=' + message + '&url=https://vegibit.com' , opts = 'status=1' + ',width=' + width + ',height=' + height + ',top=' + top + ',left=' + left ; window . open ( url , 'twitter' , opts ) ; return false ; } ) ; } ) ; var viewmodel = new Vue ( { el : '#myvueinstance' } ) ;

html

1 2 3 4 5 <div id = "myvueinstance" class = "container" > <button v-twitter = "'You gotta see how cool Vue.js is!'" class = "btn btn-info" > Share this on Twitter </button> </div>

Try it! Click the button.

Pretty cool, right?

Further Reading

Vue.js is really in it’s infancy, but developers are finding it to be very user friendly and powerful at the same time. Learn more about Vue with these great resources.

Vue.js Tutorial Summary

In this tutorial we had a lot of fun taking a look at the great Vue.js library. We covered creating a Vue instance, two day data binding, looping over data, events, filtering, components, directives, and more. Do yourself a favor and check out Vue.js today, you’ll love it!