Vue.js Tutorial

vuejs tutorial

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

js


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

js


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

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

html

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

 

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

html

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

jquery

All you need to do with Vue is this!

html

Vue js

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

js


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

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

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

js

At this point, our browser is outputting the following:

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:

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.

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

html

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

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

html

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.

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

html

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!