Checkout the Vue — A Beginners Introduction to Vue.js

Deepak Kapoor
Frontend Weekly
Published in
7 min readJul 14, 2017

These days, whenever someone tells me how great is the JavaScript framework they are working with, my immediate and biased reaction, is Oh no! Not another JS Framework.

I had a similar view (pun intended? You decide) about Vue.js. I told myself that I will wait till Vue.js gains popularity and then maybe I will have a look. After all, I was and I am still enjoying working with React.

A few months ago I had a chance to look at some Vue.js code for a project a friend was working on. This motivated me to dig deeper into Vue. I liked what I saw.

This article is an outcome of notes that I made when I first got into Vue.js. It talks about some of the basic concepts one should be familiar with when starting their journey with Vue.js.

What is Vue?

Let’s start by defining what Vue.js is. It is a library for the view layer. This is what React is. Vue.js also works with Virtual DOM which gives it the performance it claims. It provides much smarter updates to DOM by only rendering what needs to be rendered.

Vue.js resembles React more than Angular which is a complete framework.

Checking out the Vue or Hello World

Below is the minimal code you need to get a Vue.js application up and running. This simple piece of code creates a Vue instance which includes data object. Within data, we have a greeting property. Value of this property is displayed in the template using interpolation.

data is passed in as an option when creating a Vue instance. Another option is el. This tells Vue that you want to display your Vue application in the element with an id of the app.

Very basic Vue.js app. Think Hello world.

<div id="app">
{{ greeting }}
</div>
new Vue({
el: '#app',
data: {
greeting: 'Hi there! Checkout the Vue!'
}
})

Vue Templates

Templates in Vue are written in HTML. A basic template looks like this

<div id="customer">
<span>Customer Name: {{ name }}</span>
</div>

In this template, we are using interpolation to replace {{ name }} with the value of name property in the data object.

Vue templates can also render raw HTML in templates. Not a very good idea, but it can be done.

We can also use JavaScript expressions in templates. For example, to print a date, we can use this template.

<div id="app">
<span>Today is: {{ new Date().toDateString() }}
</div>

Data binding

Before we look into data-binding, it is worth talking about directives. Directives in Vue provide functionality which is not part of standard HTML. An example of a directive is v-bind which is used to bind data values. Another example is v-for which can be used to iterate over collections. We will look at conditionals soon.

Data binding in Vue is achieved with directives. To be precise, we are talking about 2-way data binding. Let us look at an example.

<div id="app">
<span>Say your name: </span>
<input type="text" v-model="userName" />
<br/>
<span>Hello <strong>{{ userName }}</strong></span> How are you today?
</div>
new Vue({
el: '#app',
data: {
userName: 'Deepak Kapoor'
}
})

Here we are using the v-model directive to establish two-way data binding with data object’s userName property. userName is also displayed in a span using interpolation. As you will expect when we update the name in the input field, the change is reflected in the span element.

Style bindings

While we are on the topic of bindings, let us look as style bindings. The directive to be used here is v-bind. Let’s build an example. We will display different colours based on the value of the signal. A signal is just a property on the data object. We will display red colour when the signal is stop, orange when the signal is wait and you get the idea.

<div id="app">
<div class="signal"
v-bind:class="{ 'red': signal === 'stop', 'orange': signal === 'wait', 'green': signal === 'go'}"></div>
</div>
<style>
.signal {
height: 20px;
width: 40px;
}
.red {
background: red;
}
.orange {
background: orange;
}
.green {
background: green;
}
</style>
new Vue({
el: '#app',
data: {
signal: 'go'
}
})

There is another syntax which can be used when applying multiple css classes as we are doing here. Note how the signal class is always applied along with the class for stop, wait or go.

<div id="app">
<div v-bind:class="[{ 'red': signal === 'stop', 'orange': signal === 'wait', 'green': signal === 'go'}, 'signal']"></div>
</div>
<style>
.signal {
height: 20px;
width: 40px;
}
.red {
background: red;
}
.orange {
background: orange;
}
.green {
background: green;
}
</style>

Code above will always apply the signal class plus the appropriate class to set the colour.

Input

We can expand the traffic lights example above by using a select element which will allow the user to select a signal.

We will now look at how form elements can be bound to data properties.

In the example below, we have a select element with four options. Based on the option selected we apply the appropriate CSS class.

<div id="app">
<select v-model="signal">
<option disabled value="">Select Signal</option>
<option>stop</option>
<option>go</option>
<option>wait</option>
</select>
<div v-bind:class="[{ 'red': signal === 'stop', 'orange': signal === 'wait', 'green': signal === 'go'}, 'signal']"></div>
</div>
<style>
.signal {
height: 20px;
width: 40px;
}
.red {
background: red;
}
.orange {
background: orange;
}
.green {
background: green;
}
</style>
new Vue({
el: '#app',
data: {
signal: ''
}
})

Here is a pen to play with

Conditionals

Vue offers the standard conditionals as directives which can be used in rendering. There are 4 conditional directives available:

  1. v-if
  2. v-else
  3. v-if-else
  4. v-show

Let’s see them in examples.

<div id="app">
<span v-if="weather === 'sunny'">Good</span>
<span v-else>Bad</span>
</div>
new Vue({
el: '#app',
data: {
weather: 'sunny'
}
})

Here we are displaying the string “Good” if the weather is sunny. We are also using the v-else directive which displays “Bad” if the value of weather is anything other than “sunny”.

We can also use v-if-else to display another value. For example, if the weather is cloudy we can display “I can live with it”.

<div id="app">
<span v-if="weather === 'sunny'">Good</span>
<span v-else-if="weather === 'cloudy'">I can live with it</span>
<span v-else>Bad</span>
</div>
new Vue({
el: '#app',
data: {
weather: 'cloudy'
}
})

Similarly, v-show can also be used to hide or show elements.

<div id="app">
<span v-show="weather === 'sunny'">Good</span>
</div>
new Vue({
el: '#app',
data: {
weather: 'sunny'
}
})

The difference between v-show and v-if is that v-show will set the display property of the element to none. The element will still be present in DOM. On the other hand, v-if will not render the element. Something to be aware of when rendering a large number of elements.

Here is a codepen to play with.

Lists

Lists are a very common way to display information in applications. Vue comes with excellent support for displaying lists. It provides a v-for directive which can be used to loop through collections in templates and render required elements.

In the example below, we are rendering a list of Australian (yes I am from Australia) states.

<div id="app">
<ul>
<li v-for="state in states">
{{ state.code }} - {{ state.name }}
<li>
</ul>
</div>
new Vue({
el: '#app',
data: {
states: [
{ code: 'NSW', name: 'New South Wales'},
{ code: 'VIC', name: 'Victoria'},
{ code: 'ACT', name: 'Australian Capital Territory'},
{ code: 'QLD', name: 'Queensland'},
{ code: 'NT', name: 'Northern Territory'},
{ code: 'WA', name: 'Western Australia'},
{ code: 'SA', name: 'South Australia'},
{ code: 'TAS', name: 'Tasmania'}
]
}
})

Event handling

What is an application if a user cannot interact with it? Any interaction that occurs on UI results in events being fired. These events can be handled and we can take actions. The way to handle events in Vue is by using v-on directive.

Let’s look at a basic example. In this example, we increment a counter whenever a button is clicked.

<div id="app">
<button v-on:click="counter++">Increment counter</button>
<p>Counter is at {{ counter }}</p>
</div>
new Vue({
el: '#app',
data: {
counter: 0
}
})

Normally we would do a bit more than incrementing numbers. For example, we could call a function which gets data from an http end-point and displays it to the user. We could also find factorial of a number. Let’s try that.

<div id="app">
<input type="text" v-model="num" />
<button v-on:click="getFactorial">Get Factorial</button>
<span>Factorial of {{ num }} is {{ factorial }}</span>
</div>
new Vue({
el: '#app',
data: {
num: 0,
factorial: 1
},
methods: {
getFactorial: function (event) {
let num = this.num
this.factorial = computeFactorial(this.num)
}
}
})
const computeFactorial = (num) => {
if (num === 0) {
return 1;
}
return num * computeFactorial(num - 1);
}

We will examine the code above.

Here we see that we have created another option called methods when instantiating Vue. Within the methods object we have created a property getFactorial which is a function. We can wire up the function in our template. getFactorial just calls a utility function to compute the factorial.

getFactorial function receives an event object. We are not using it in this function but it gives us useful properties like target, type etc.

Also, this keyword is bound to the Vue object which is being instantiated here. That is how we have access to data properties.

Computed Properties

Computed Properties are passed into the Vue instance as an option. They do the same thing as methods i.e. they invoke a function. So why do we have them? Because they provide caching.

Let’s look at an example in which we will convert temperature from Celsius to Fahrenheit. Here we use computed property which is dependent on a data property.

<div id="app">
<input type="text" v-model="celsius" />
<p>
{{ celsius }} Celsius = {{ celsiusToFahrenheit }} Fahrenheit
</p>
</div>
var vm = new Vue({
el: '#app',
data: {
celsius: 0
},
computed: {
celsiusToFahrenheit: function() {
return this.celsius * 9 / 5 + 32;
}
}
})

In Conclusion

This article you can say scratched the surface of Vue.js. There is a lot more that Vue offers. In another article I will write more about Vue ecosystem, tools, components, debugging etc. An understanding of these concepts is essential for developing real-world applications. Stay tuned.

Thanks for reading.

If you found this article useful, then please like it. It will make the world a better place :)

--

--