<img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=160269078105920&amp;ev=PageView&amp;noscript=1">

What is Vue.js and How do we Use It?

Tuesday 26 of November, 2019.
Reading Time: 10 minutes.
By Miguel López Mamani

As Front-End Developers, we usually want to choose the most appropriate technology for each of our projects in order to improve how we write and organize code. Therefore, the main goal of this article is to review the main features of Vue.js, a progressive JavaScript framework, that allows us to quickly develop single-page applications (SPAs) that are easily maintained while using its components and reactive features, such as reactive interfaces and data binding.

1200px-Vue.js_Logo_2.svg

What is Vue.js?

Created by Evan You, Vue.js is an open-source progressive JavaScript framework for building user interfaces (UIs) and single-page applications; it is commonly referred to as Vue. This framework uses “high decoupling”, allowing developers to progressively create user interfaces (UIs).

 

Why Vue.js?

Library modularization using a framework is common in frontend development. Both React and Angular have modularization. But what differentiates Vue.js from other alternatives is its “high decoupling”, how easy it is to extend functionalities, and how well all parts work once more modules are included. For example, if we want to organize and render small visual components, all we need is Vue.js’s ‘core’ library; it is unnecessary to include additional libraries. As the application grows, we have libraries to manage routes such as ‘vue-router’, libraries to manage the global state such as ‘vuex’ or libraries to build responsive web applications such as ‘bootstrap-vue’. Additionally, if our application needs to be optimized or needs good SEO, we can include the ‘vue-server-rendering’ library. In the following figure, we can see how the libraries we just mentioned are progressively included, from a small SPA to multi-page applications (MPA).

Screen Shot 2019-11-14 at 4.05.40 PM

Vue.js’s component system is reactive, which means that Vue.js knows how to communicate through asynchronous events; for example, a child component can communicate with its parent component through events. With Vue.js there is no friction with other libraries or resources, in other words, we can use the tool with which we are most comfortable with. For example, we can write only HTML and JavaScript or if we want we can add CSS, JSX or TypeScript.

Vue.js has a special command line (CLI) created on Node JS. This tool allows us to start a project using a boilerplate (or base template). Additionally, the Vue.js development team maintains a Chrome extension that allows us to see how our component tree is rendered, how events are being launched and recorded, how the internal state of each component is saved, and how the global state of the component is behaving.

Who is Using Vue.js?

More than 700 companies are using Vue.js. Some of the most important are: Xiaomi, Alibaba, and Gitlab. The complete list is available at https://stackshare.io/vue-js/in-stacks.

Screen Shot 2019-11-14 at 4.05.52 PM

Developing with Vue.JS

Environment Setup

There are different ways to include Vue.js in your web project:

● Downloading the Vue.js file and including it with <script> tag directly in the HTML file

● Using CDN by including <script> tag in the HTML file

● Installing it using Node Package Manager (NPM)

● Using Vue-cli to set up your project

In the following example, we use CDN, where the <div> tag contains the template code, the <script> tag contains the script code, and the <style> tag contains the CSS code.


<html>
	<head>
    	<title>Simple Vue.js Example</title>
        <script src="https://cdn.jsdelivr.net/npm/vue"> </script>
    </head>
    <body>
    	<div id="app">
        	<p> message  Avantica Blog Visitors!</p>
        </div>
        <script>
        	var app = new Vue({
            	el: '#app',
                data: {
                	message: 'Hello'
                }
            });
        </script>
        <style>
        	p {
            	font-size: 2em;
                text-align: center;
              }
        </style>
    </body>
</html>

Screen Shot 2019-11-14 at 1.08.36 PM

Please note that in the previous code example, an instance of Vue was created with the syntax ‘new Vue()’. This instance has an option called ‘el’, which refers to the <div> tag where the template code is located; so the ‘data’, which contains the application attributes, can be rendered inside the <div> tag. Other options that an instance of Vue accepts are: 'computed', 'watch', 'methods', and lifecycle hooks, where the 'computed' option contains the getters or setters of the 'data'; the 'watch' option contains the observers of the 'data'; the 'methods' option contains the behavior or functions of the Vue application; and the lifecycle hooks such as 'created', 'mounted' or 'destroyed' are life cycle states of the Vue.js instance.

If we want to create a Vue.js project using NPM, which is recommended for large scale applications, we can install the latest stable Vue.js using the following command:


> npm install vue

Then, we can create a Vue.js project using:


> vue create my-first-vue-app

Declarative Rendering

The core of Vue.js allows us to declaratively render data to the DOM using a simple template syntax:


<div id="app">
	 message 
</div>

<script type="text/javascript">
	var app = new Vue({
    	el:'#app',
        data: {
        	message: 'This is the Avantica Blog!'
        }
    })
</script>

Screen Shot 2019-11-14 at 4.09.19 PM

Please note that Vue.js evaluates the statement declared by double curly braces , so the ‘data’ object from the Vue instance is rendered into the string template . Therefore, the data object and the DOM are linked, and everything is now reactive. We can confirm this by opening our JavaScript console and setting app.message to a different value.

Directives

Directives are special attributes with the v- prefix (such as v-if, v-else, v-show, v-bind, and v-model) that allow us to manipulate the DOM. For example:


<div id="app">
	<p v-if="shown">You can see this message.</p>
</div>

<script type="text/javascript">
	var app = new Vue ({
    	el: '#app',
        data: {
        	shown: true
        }
    });
</script>

Here, the v-if conditional directive removes or inserts the <p> element if the value of the expression ‘shown’ is true. If we enter app.shown = false in our JavaScript console, we should see the message disappear. So, we can bind data for the structure of the DOM.

Some directives can take an “argument”, denoted by a colon after the directive name. For example, the v-bind directive is used to reactively update an HTML attribute. Below, the ‘placeholder’ is an argument that tells the v-bind directive to bind the element’s ‘placeholder’ attribute to the value of the expression ‘expectedValue’.


<div id="app">
	<input v-bind:placeholder="expectedValue" />
</div>

<script type="text/javascript">
	var app = new Vue ({
    	el: '#app',
        data: {
        	expectedValue: 'edit me'
        }
    });
</script>

Here, it is keeping the element’s ‘placeholder’ attribute up-to-date with the ‘expectedValue’ property on the Vue instance. If we enter app.expectedValue = 'write here ...' in our JavaScript console we will see that the bound HTML has been updated, in this case, the ‘placeholder’ attribute.

Loops

The v-for directive is used to display a list of items using the data from an Array. In the following example, we display a list of Avantica locations by populating the Array ‘locations’. If we enter app.locations.push({ text: 'Cochabamba, Bolivia' }) in our JavaScript console, we can see a new item appended to the list.


<div id="app">
	<ul>
    	<li v-for="location in locations">
        	 location.text 
        </li>
    </ul>
</div>

<script type="text/javascript">
	var app = new Vue ({
    	el: '#app',
        data: {
        	locations: [
            	{ text="Silicon Valley, USA" },
                { text="San Carlos, Costa Rica" },
                { text="Lima, Perú" }
            ]
        }
    });
</script>

Event Handling

In order to interact with users, we can use the v-on directive to attach event listeners that invoke methods on our Vue instances. In the following example, when the user clicks on the button, the Vue method is invoked (called ‘showPhone’) and displays a window message with the Avantica Phone number. Vue.js provides shorthand notations for event listeners, so we can replace ‘v-on:’ with ‘@’.


<div id="app">
	<button v-on:click="showPhone">Show Avantica phone </button>
</div>

<script type="text/javascript">
	var app = new Vue ({
    	el: '#app',
        methods: {
        	showPhone: function () {
            	alert('+1 650-641-3134');
            }
        }
    });
</script>

Screen Shot 2019-11-14 at 1.08.50 PM

Data Binding

Vue.js provides the v-model directive that creates a two-way binding between form input and the app state. In this example, the statement and the ‘data’ object are linked. If we enter app.message = 'Hello again Visitor!' in our JavaScript console, we will see that the string text template and the value of the <input> have been updated.


<div id="app">
	<p> message </p>
    <input v-model="message">
</div>

<script type="text/javascript">
	var app = new Vue ({
    	el: '#app',
        data: {
        	message: 'Hello Visitor!'
        }
    });
</script>

Reactive Interfaces

Vue.js also provides options to add reactivity to properties, which are added dynamically, by using the watch property, that works as an observer. In the following example, every time a user changes the value of the ‘counter’ data by clicking on the button, a message is displayed showing the old and the new value of ‘counter’:


<div id="app">
	<p>Counter:  counter </p>
    <button @click = "counter++">Increment Counter</button>
</div>

<script type="text/javascript">
	var app = new Vue ({
    	el: '#app',
        data: {
        	counter: 1
        },
        watch: {
        	counter: function(new_val, old_val) {
            	alert('Changed from' + old_val + ' to ' + new_val + '!');
            }
        }
    });
</script>

Screen Shot 2019-11-14 at 1.08.59 PM

Computed Properties

Expressions in the template are very convenient for simple operations because including too much logic in our templates can generate code smell, which makes it hard to maintain. Hence, we can use a computed property, which is basically a getter function that always depends on the associated value of the ‘data’ object. Here’s an example:


<div id="app">
	<p>Original message: " message "</p>
    <p>Computed message: " reversedMessage "</p>
</div>

<script type="text/javascript">
	var app = new Vue ({
    	el: '#app',
        data: {
        	message: 'Avantica'
        },
        computed: {
        	reversedMessage: function() {
            	return this.message.split('').reverse().join();
            }
        }
    });
</script>

Here, we use a computed property called ‘reversedMessage’ where the value of app.reversedMessage is always dependent on the value of app.message. You can bind data to computed properties in templates just like a normal property. Vue.js is aware that app.reversedMessage depends on app.message, so it will update any bindings that depend on app.reversedMessage when app.message changes.

Components

The Vue.js component system allows us to build large-scale applications composed of small, self-contained, and reusable components. Since components are reusable Vue instances, they accept the same options as new Vue, such as data, computed, watch, methods, and lifecycle hooks. The following figure shows how a typical application interface is abstracted into three components: header, sidebar, and body.

Screen Shot 2019-11-14 at 4.06.00 PM

The following is an example of how to use a Vue component called <button-counter>:


<div id="app">
	<button-counter></button-counter>
    <button-counter></button-counter>
    <button-counter></button-counter>
</div>

<script type="text/javascript">
	Vue.component('button-counter', {
    	data:function () {
        	return {
            	count: 0
            }
        },
        template: '<button v-on:click="count++">You clicked me  count  times.</button>'
    });
	var app = new Vue ({
    	el: '#app'
    });
</script>

Here, we create a component with the syntaxis: Vue.component, where the first parameter is the name of the component and its options are: ‘data’ and ‘template’. Vue Components can be reused as many times as we want; in the example, we use <button-counter></button-counter> three times. Notice that when clicking on the buttons, each one maintains its own, separate count. This is because each time you use a component, a new instance is created.

Conclusion

And that’s it! Using a little Vue.js API, we have created a single-page application (SPA) that automatically updates the view based on the ‘data’ object changes of the Vue instance, keeping the view synchronized while using Vue.js components and reactive features such as directives, declarative rendering, data binding, reactive interfaces, and computed properties.

References

  1. Vue.js Guide. Taken from: https://vuejs.org/v2/guide/
  2. SPA vs MPA. Taken from:
    https://medium.com/@jainshilpa1993/ultimate-death-match-spa-vs-mpa-82e0b79ae6b6
  3. Por qué elegir VueJS: 5 razones para considerarlo nuestro próximo framework de referencia. Taken from:
    https://www.genbeta.com/desarrollo/por-que-elegir-vuejs-5-razones-para-considerarlo-nuestro-proximo-framework-de-referencia
  4. Vue.js Server-Side Rendering Guide. Taken from https://ssr.vuejs.org/
  5. Vue.js tutorial. Taken from: https://www.tutorialspoint.com/vuejs/index.htm

 

About Avantica

If you are looking for a software partner who will work towards your own business goals and success, then Avantica is your solution. We offer dedicated teams, team augmentation, and individual projects to our clients. We are constantly looking for the best methodologies in order to give you the best results.

Like What You Read? Get in Touch!

 

 

About the author

Blog-Template-[Recovered]-2

PREVIOUS
UX/UI: Expense or Investment?
NEXT
Indecomm Digital Strengthens Nearshore Presence with the Acquisition of Avantica Technologies