Getting Started with Vue.js: Why Use it?
Vue.js is yet another JavaScript UI library that is making waves and has growing support from the community. If you have an upcoming project and are wondering which tool to choose, you can give Vue a try.
Vue is considerably easy to learn and you can get started with it in just 10 minutes (actually, that is what this article is going to help you do). But first, let’s have a quick look at why you should even give Vue a try.
Read more: Skills JavaScript Developers Should Learn in 2016
Why use Vue?
The idea behind this article is not to try to convince you on whether to use Vue or not. Neither is it supposed to start an argument on whether or not it is better than other tools out there. Rather, the purpose is to show you how simple it is to get started with Vue.js and maybe, it could save you a deadline.
When comparing it with its competitors, including Angular, React, Ember, Aurelia, etc., Vue boasts of beating some of them in certain aspects. These aspects include simple API, size, performance, learning curve, etc. You can have a look at these comparisons on the official documentation.
And as you may or may not know already, the most important of all is not these tools—it’s really about you, your client, your team, and the project. It is recommended to choose what blends in well and if Vue does, read on.
Requirements
Vue requires as little as just a single script to experience its awesomeness. And for this tutorial, we can make use of Fiddle and we need not acquire the luxury of tooling on our machine to start building. This will also help us see some of our code come to life, instantly.
Create an empty Fiddle and add the following script to the HTML:
<script src="https://unpkg.com/vue@next/dist/vue.js"></script>
The script loads Vue into the Fiddle environment and from now on, we can use whatever API Fiddle can offer.
The Vue Instance
The entry point of every Vue application is created via an instance. The instance then configures the rest of the application and can drill into child members while your application scales up. This is how one would look like:
// Vue instance
new Vue({
// Element to attach the app
// on the DOM
el: '#app',
// Bindable data
data: {
message: 'Welcome to Codementor!',
}
})
The instance is configured by passing in an object containing information about the app and where it should be loaded.
The el
property specifies which element it should be mounted on and the value is the ID of the element prefixed with a hash (#).
The data to be bound to the view is specified with the data
property, which has an object of values that can be accessed via the template.
Back in the HTML, we can display the data using what is called reactive binding:
<div id="app">
<p>{{ message }}</p>
</div>
Two things worth noticing
the div with the ID app
is where we mount the application; and
the double curly braces are used to bind the data to the template.
We are binding the message
value which is specified in the data
object during configuration.
Getting started is that simple and we already have a working app without the drama:
Data-Binding
We already saw a good example of binding data to view but there is more to that in a real application. Let’s drill it down more and see what Vue can do for us:
Conditions
A very useful feature in JS frameworks is the ability to bind data to view prior to a decision. We can tell Vue to make a binding only if a value resolves to true
. Let’s see how:
new Vue({
el: '#app',
data: {
message: 'Welcome to Codementor!',
// Flag to check if user
// is a new member or not
newMember: true
}
})
We just added an extra data to check if the user is new or not. If it’s true
that the user just joined, else he/she is not a new member.
Let’s use the flag to display different messages to Codementor users:
<div id="app">
<!-- Shown if the user is new -->
<h2 v-if="newMember">{{ message }}</h2>
<!-- Shown if the user is NOT new -->
<h2 v-else="newMember">Pick a Mentor</h2>
</div>
v-if
and v-else
are responsible for displaying data conditionally. If the value being evaluated (which is newMember
) resolves to true
, the template with the v-if
directive wins, if false
, v-else
wins.
Loops
Vue is awesome enough to offer us a simple API to loop through an array of bound data. The v-for
directive takes its use for this purpose and all we just need is an array of data:
<ol>
<li v-for="mentor in mentors">{{mentor.fullname}}</li>
</ol>
v-for
accepts a loop expression which creates a variable mentor
and uses the variable to iterate over an array of mentors
. The array contains the object so we can then access the properties:
new Vue({
el: '#app',
data: {
message: 'Welcome to Codementor!',
newMember: false,
// Array of mentors
mentors: [
{id: "ABC", fullname: "Arup Rakshit"},
{id: "DEF", fullname: "Mo Moadeli"},
{id: "GHI", fullname: "Khaja Minhajuddin"},
{id: "JKL", fullname: "bendozy"},
{id: "MNO", fullname: "Massimo Frascati"},
{id: "PQR", fullname: "Christian Nwamba"}
]
}
})
You can see the array that contains a list of mentors which the v-for
directive is iterating over.
Two-Way Binding
Two-way binding in Vue is very straight forward and is achievable with just a directive known as v-model
. Let’s see two-way binding in play by attaching the v-model
directive to a text input and display the data at the same time:
<p>
Add mentor: <input type="text" v-model="mentor">
{{mentor}}
</p>
The value of the directive is used for the data-binding and that is why the content of the interpolation ({{}}) is the same with that of the directive. We now need to specify the data in our Vue configuration:
new Vue({
el: '#app',
data: {
message: 'Welcome to Codementor!',
// For the two-way binding
mentor: '',
newMember: false,
mentors: [
// Truncated for brevity
]
}
})
Events and Handlers
Event is the story behind user interaction in any web application. For that reason, Vue has a very declarative syntax which is simple to comprehend and remember for creating and handling events.
Let’s first add more controls to our view which we will use to collect the mentor’s full name and ID.
<p>
ID: <input type="text" v-model="mentor.id">
{{mentor.id}}
</p>
<p>
Fullname: <input type="text" v-model="mentor.fullname">
{{mentor.fullname}}
</p>
<p>
<button v-on:click="addMentor">Add Mentor</button>
</p>
Just the usual binding but this time, we are binding to the values of an object and not just a direct primitive value.
Furthermore, we also added a button to an event. Events in Vue are created with the v-on
directive while attaching the kind of event using :
. Eg: v-on:click
, v-on:mouseover
, etc. The click event takes a handler, addMentor
which we are yet to implement. Before the implementation of this event, update the mentor
data in the Vue config to an object rather than a primitive:
mentor: {id:'',fullname:''},
Event handlers are specified just like bound data are but not directly inside the data object, rather, in a methods object:
new Vue({
el: '#app',
data: {
message: 'Welcome to Codementor!',
// No longer a primitive
mentor: {id:'',fullname:''},
newMember: false,
mentors: [
// Truncated for brevity
]
},
// Methods
methods: {
// Add mentor handler
addMentor: function(){
// Add new value from the inputs
// above the existing array
this.mentors.unshift(this.mentor)
}
}
})
The addMentor
property has a function value which tells our app what to do when the button is clicked. What it does is update the array of mentors by dropping our new mentor above the array using unshift
.
Meet Components
If your concern is whether or not you can enjoy components just like you do in other frameworks or libraries, then you can stop worrying because you can. In fact, components are recommended in Vue projects because just as we can see, our app is already getting bigger.
Let’s create a mentor-user
component that just receives data from our app and displays the data:
// mentor-user component
Vue.component('mentor-user', {
// acceptable props
props: ['mentor'],
// renderable templates
template: '<li>{{mentor.fullname}}</li>'
});
Components are created with Vue.component
which takes two arguments — a component name/identifier and a configuration.
The config object specifies the template that the component will inject to the DOM and the props expected from the parent of the component. The parent is that itself so let’s see how the parent calls it:
<ol>
<mentor-user v-for="mentor in mentors" v-bind:mentor="mentor"></mentor-user>
</ol>
We render the component using the identifier specified while creating the component. We also pass in the props using v-bind:[PROP_NAME]
where PROP_NAME is the name the property and in our case, mentor
. The value of the property is received from the loop.
This might not seem so useful for the size of our app but once an app scales, the portion taken care of by the component might require more and more DOM items.
Summary
As you have seen, it is very easy to get started with Vue and in fact, simplicity is what Vue boasts of. Vue has taken a look at the downsides of other frameworks and tried to make things better, which makes it worth giving a shot or even worthy of considering.
Related tutorials you could be interested in:
- React vs AngularJS vs KnockoutJS: a Performance Comparison
- React vs AngularJS – How the two Compare
- What Should Beginners Choose: AngularJS, Ember.js, or Backbone.js?