iJS CONFERENCE Blog

An Introduction to Vue.js

Triumph of a framework

Aug 14, 2018

Vue.js is a framework for web applications that enables component-oriented development based on JavaScript. It’s adaptable, especially lean and universally applicable. Of course, Vue.js is also very performant. So, it’s high time that we take a closer look at this framework. In part one of this two-part tutorial, we give a systematic introduction for the popular JavaScript framework.

In this two-part introduction for Vue.js, we want to take a detailed look at the JavaScript framework and its functionality. In the first part of the tutorial, we’ll get an overview on this framework, focusing on how to distinguish Vue.js from other frameworks. In the second part of the tutorial, we’ll get down to business and show you how to develop components in Vue.js with the help of some code examples.

The second part of this article can be found here →

 

Tutorial Vue.js – A triumph of a framework

The future belongs to the web applications. Actually, anyone who has taken a look at web development in recent years has already come to this conclusion. The increasing digitalization in all areas of life and the explosive spread of social networks, accompanied by the provisioning of mostly mobile and resource efficient UIs, play positively into the hands of languages such as HTML5, CCS, and JavaScript. Certainly, the classic Rich Client will never completely disappear, as it can be implemented in environments such as JavaFX or the Eclipse Application Platform, nor should it.

But at least we have to admit it, if we are being honest: web applications in general have established themselves almost everywhere. The reason for that is the universal applicability of the underlying technologies of so many different devices: from TV sets, PCs, notebooks, tablets to mobile phones. This is exactly the direction in which things will continue to go.

Go for JavaScript!

JavaScript in particular benefits from this web development. Right now, there is a lot happening in the JavaScript world. In this regard, innovation and great commitment from various development communities are clearly visible. Web applications have been around for a long time, but they were more server-centric in the past. Large enterprise applications, which were implemented on a foundation of Java EE, quite often use technologies such as Servlets, JSP, and JavaServer Faces. What these techniques have in common is that they do generate their results (which are mostly HTML pages) on the server side and this out was only displayed on the client (mostly in the browser).

But is there any interactivity on the client? Well, in most cases you won’t have such luck. Furthermore, JavaScript was even frowned upon. Fortunately times have changed. Developers began to modernize their existing applications with JavaScript, making them more interactive, and above all, more dynamic. The possibilities of the browser were more and more inclusive.

Still, as great as these newly won freedoms were, they quite often led to another problem in the increasingly complicated code-base of such a JavaScript modernized web application. Suddenly, JavaScript code could be found anywhere, bustling in many different files and in the most unusual and impossible of places within the project. This makes the maintenance of such an application turn into a real challenge.

Yet on the other hand, companies such as Facebook, Twitter or Google went into new directions. They decided to run more and more components of a web application directly in the browser. The idea around the so-called Single Page Applications took on a concrete form. Google Docs or Gmail are good examples of this development.

Standards, structure, and continuity

No matter how you look at it, frameworks are important. Whether we want to bring structure into a legacy web application that has been extended with JavaScript or if we want to write a whole new single page application that runs completely in the browser, frameworks help us. Frameworks give us structure, standards and continuity for our application development.

Therefore, it is no wonder that frameworks are springing up like mushrooms, especially in the innovation-driven environment of JavaScript. Some frameworks for the development of web applications based on HTML5, CSS and JavaScript have become established, while others have disappeared. Toolboxes like Angular or React turned into real top dogs. In particular, React is enormously successful and enjoys an increasing attention. The box titled “Web Components” gives a detailed explanation, as to why this is the case.

Web components

The internet has changed rapidly since 2010. Companies such as Facebook, Twitter, or Google have started to do far more than just publish websites or homepages. Their products have become more and more refined. Complete applications were produced to run interactively and dynamically in the browser and feel native. Single Page Applications started their victory march.

However, the developers who had to implement these applications faced huge challenges. At the time, the programming of web applications was mostly done on the server. The Spartan approach of HTML elements such as <p>, <form> or <div> was stifling developers even further. In the end, new combinations of those aforementioned elements were developed and augmented with CSS or JavaScript. HTML5 has improved the situation, but developers still need to be able to develop reusable components manifested in their own HTML elements.

The WC3 consortium, which is known for being responsible for both the maintenance and the further development of standards like HTML or CSS, recognized this need. They put forth the prospect of an HTML expansion. The web components were on their way. Unfortunately, the W3C has failed to push this new standard and to give to the people for many years now. They have missed out on a very important opportunity here; in the meantime, big companies like Google and Facebook have acted out of necessity and have put forth their own vision of the Web Component into practice.

Angular, React, and later Vue.js were all created this way. All these frameworks do not follow an actual standard and are not an official implementation of the Web Components. They have still spread very fast. Now the question of who will ultimately win the race has yet to be answered. As to whether the official standard of the W3C will ever become generally accepted, it also remains to be seen.

Vue.js – an introduction

Vue.js is another, somewhat smaller framework, which is drawing in increasingly more attention. It is a framework for that we can develop component-oriented web applications, based on JavaScript. Actually, just like you can do it with Angular or React. The Vue.js developers describe their framework very aptly: “An approachable, versatile, performant web framework that helps to write maintainable and testable applications.”

Vue.js can be used to modernize existing web applications. It has no problem to selectively bring small parts of the application under the control of Vue.js and then to add more parts bit by bit. Now, the next logical step would be to implement new extensions based on Vue.js. So, if you are lucky enough to start a completely new project, then you can also build it completely on the basis of Vue.js.

Due to Vue.js’ character, developers are ensured to move within a defined framework. This is also reflected in a comprehensive project structure and a standardized, uniform programming model. It’s a great added value. These possibilities are one of the strengths of Vue.js, because this is exactly where its universal applicability, approachability, and versatility come into its own.

If you want to run more business logic on the client (keyword: single page application), then you can also built the entire application based on Vue.js. The framework comes with all the necessary components in the form of the Vue Core, Vuex and Vue Router modules. A description of the individual modules can be found in table 1.

What is important to understand is that only Vue Core is mandatory – the other modules can be added as needed. In principle, no installation is required in order to write a Vue.js application. Theoretically, it is sufficient enough to download the JavaScript libraries of the individual components from the Vue.js website [1] and to integrate them into your own application by using the <Script> tag. Practically nobody does this anymore, because just like there are tools for the integration of libraries into the world of Java such as Maven or Gradle, there are also similar tools for JavaScript.

The Node Packager Manager, npm, has become quite well established in this regard. It is a command line tool that is automatically provided with the installation of Node.js. Just like in Maven where the pom.xml does control the application configuration and the build, npm creates a file named package.json. This file contains information that is very similar to a pom.xml, including the dependencies of the project and information about the application build.

If you are serious about developing single page application with JavaScript, then you simply cannot avoid a tool like npm. Each of the Vue.js modules can be installed by using npm – you can find a summarization on how to do so in table 1. Now, the easiest way to start a new project is to create an empty project folder and initialize the project from there with the help of the command

npm init

After a few questions, we get the initial package.json file. Then we install – always from the project directory – the required JavaScript modules from table 1. The modules are then automatically loaded from the Internet, stored in the project, and a corresponding entry is inserted into the package.json. However, creating a new Vue.js project is even more convenient with the VUE CLI tool. This can also be installed with NPM and comes with a whole series of ready-made project templates from which you can create your project. With the command

vue init <Templates-Name> <Project-Name>

the project directory is automatically created based on the template, the corresponding dependencies are downloaded in the background, the sample source code is added and the development can begin. On the GitHub page of VUE CLI[2], you can find a very good overview of all the available templates.

To get started, it is recommended to begin with the template “simple”. For larger projects you will certainly use a bundle manager like webpack [3] at some point in time, so a look at the two templates of webpack simple and webpack should be worthwhile.

Module Description Installation
Vue Core The core component is necessary if we want to write an application. It is based on Vue.js.  It implements the Vue-object with Data Binding and provides all tools to enable the development of components. npm install –save vue

<script src=“/path/to/vue.js“></script>

Vuex Vuex is a state manager. It keeps the components of an application together and controls their status, manages data, and exchanges them between the components. Vuex can be compared to the JavaScript library Redux, which is often used in the React environment. However, the two state managers differ in detail. In Vuex, data can only be modified according to certain rules or if the components are in a specified state. Furthermore, Vuex is characterized by the same reactive character as in the core. This means that if data changes within the state manager, various lifecycle methods are run in which the developer can engage. npm install –-save vuex

<script src=“/path/to/vuex.js“></script>

Vue Router If you are programming a single page application, you need a router to switch between the individual pages. Vue Router is extremely easy to use. For this purpose, a VueRouter object is provided. We configure it with a JavaScript object so the routes and their links to the underlying components are stored. They are displayed when activating a route. npm install –-save vue-router

<script src=“/path/to/

vue-router.js“></script>

 

 

VUE CLI This is a command line tool to create new Vue.js projects from templates. It’s best to start with the simple template and then continue with the webpack templates. It is also possible to define and integrate your own project templates. npm install -g vue-cli

Table 1: The most important modules and components of Vue.js

Want more exclusive knowledge? Sign up for our newsletter now!

The origins of Vue.js

In contrast to Angular and React, which were developed by big companies, Vue was conceptualized and developed by one person. The original developer, Evan Yu, was originally a Google employee and worked on different web technologies. He was especially fascinated by Chrome Experiments [4], because he realized what kind of potential browser in general and especially programming languages like JavaScript had. He taught himself JavaScript and finally joined the Angular team. At Angular, he was enthusiastic about the possibilities of data binding and the way developers could use the DOM to handle, influence, and change the browser without having to access it directly.

Evan wondered if it would be possible to extract the small but central part from Angular that really interested him: declarative data binding. However, he did not want to copy the Angular source code, but to design and implement it himself. So he started a little experiment to create such a declarative data binding. That was the beginning of Vue.js. Evan worked on this experiment and instinctively felt that what he had created had to be good and had to have potential, since he liked to use it so much. In February 2014, he released the first version on GitHub. Within the first week, the framework was showered with praise and the download numbers went up rapidly.

A distinction from Angular and React

If you compare Vue.js with other frameworks like Angular or React, you will probably come to the conclusion that it is most similar to React. Even Yu also calls it a progressive framework. The idea behind it is that the Vue Core merely consists of an implementation for data binding and also offers the possibility of programming components. That’s it.

While Vue.js may seem similar to React, it does solve some very special problems and focus internally; Vue.js also has a much larger view on the universal applicability. For Vue.js, it is sufficient if the user is familiar with HTML, JavaScript, and CSS. They can start right away. In React, on the other hand, they will have to learn special extensions such as JSX.

The Vue.js framework was deliberately kept very slim. Other frameworks such as Angular are very broad and have a solution on board for almost every problem that can arise in the context of the application development. Vue.js focuses on slenderness and performance. Additional framework features such as routing or state management can be added as needed.

Finally, it is impossible to say which framework is the best. Whether your framework of choice is Angular, React, or Vue.js – every toolbox has its individual strengths and weaknesses. Every development team must find the right package for itself. Evan Yu says that he deliberately avoids the pressure to compete with others. For him, it is only important to do a good job and to satisfy the developers who appreciate his framework and like to use it.

Progressive and reactive

To get an overview of Vue.js, it is recommended to create a first project with the template simple and the command line tool VUE CLI:

vue init simple vue-test

This template does create a project folder vue-test and just stores an index.html in the project folder.

But if we use the webpack simple template for an example, then there are significantly more files created – such as a package.json files with some dependencies and a webpack configuration.

However, in the vue-test project there is no package.json, instead the dependency to the Vue.js library is resolved through a simple <script> directive. You can still get a rather good insight on how Vue.js works, if you take a look at the index.html.

The global Vue object that implements data binding is of central importance here. There can be one or more Vue objects. A Vue object is bound to an HTML element and takes control of that element or area in the browsers DOM from that point on. The Vue object is configured to pass a JavaScript object, which must contain a manageable number of predefined properties: el and data.

Furthermore, user-defined functions and so-called lifecycle-methods can be added. The el property binds the Vue element to the HTML element. In the example project, the Vue object is bound to the <div> element with the ID app. The data property is of central importance. Herein is all the data that is managed by Vue.js. Once the data is available here, it is included into the Vue.js reactivity system. This means that Vue.js automatically updates the relevant HTML elements associated with the data inside the DOM, every time when the dataset is changed.

Functions with their own business logic (in the example it’s the humanizedURL function) can be inserted as an element of the listing methods. These can be any number of functions. If we open the development tools in the browser (Chrome, Firefox), we have the possibility to analyze the Vue object, to change it, to call methods on it, etc., via the JavaScript console at runtime. This greatly simplifies the handling and development of Vue.js applications.

In the example project, the Vue object is kept in a variable app, so that we can access the app object directly in the JavaScript console at runtime. The data components are directly accessible as properties: app.greeting would therefore output the corresponding text. But your own methods are also available; the app.humanizedURL method can be called directly without any problems.

Lifecycle and watchers

It can get even better. When a Vue object is created and started, it goes through a life cycle as shown in figure 1. It is quite important to understand, that you can hook into every moment of this life cycle with the already mentioned lifecycle methods (depicted in the red illustration).

This allows the user to use the mounted-method to be informed or to react when the Vue object (or the Vue component) is completely initialized. This can be quite useful if you want to carry out your own initialization afterwards. There are also corresponding lifecycle methods for changing data. The methods beforeUpdate and updated could also be interesting here.

Fig. 1: Vue.js Lifecycle. Source: Official Vue.js Documentation

The data from the Vue.js instances can be displayed as simple properties, as previously mentioned. But we can also change or reset them; this means that the lifecycle shown in the figure is either being run again entirely or partially. For example, if we put app.greeting =”Hello World” in the console, the data on the interface would change immediately (reactivity!), but the already mentioned lifecycle methods beforeUpdate and updated would also be called.

Vue.js instances offer a number of other interesting instance properties and methods for monitoring and querying the state of the Vue.js instance. These special properties and methods all start with the prefix $, so that they are clearly separated from the user-defined data and methods.

Here are two examples: app.$data would output the complete data object of the instance, and app.$el the HTML element to which this Vue.js instance is bound. Here, it is recommended to enter app.$ once in the Chrome browser in the developer tools console and wait for the code completion. What is on offer here is quite amazing and interesting.

Finally, Watcher can also be bound to a Vue.js instance. This is done using the $watch help method:

app.$watch(‚greeting‘, function (newValue, oldValue) {

 console.log(‚Old=‘ + oldValue + ‚ New=‘ + newValue);

});

This allows the developer to be informed about every change, every call to a specific property or method of the Vue.js instance and to react individually. For example, the Watcher above is called, whenever the corresponding data changes.

Vue.js Tutorial – Part 1: Intermediate conclusion

The future belongs to the web applications. Therefore you are well advised to engage with JavaScript. This language is still growing and it can be used with frameworks like Angular, React, or Vue.js. Toolkits are available with to write scalable, extensible, high-performance and component-based web applications.

In this tutorial, we covered the basics of Vue.js, where the framework comes from, and how it positions itself between the top dogs Angular and React. We have examined the basic structure of Vue.js applications and presented their basic concepts. As in the other web frameworks, it is possible to develop reusable and independent components with Vue.js. Just like Angular and React, Vue.js does not follow the official Web Components standard here, but comes with its own individual implementation of components. In the second part of this tutorial, we will see how to develop component-oriented web applications with Vue.js.

Read more in the second part of this article →


Links

[1] Offical Vue.js-Web site: https://vuejs.org/
[2] vue-cli- command line tool: https://github.com/vuejs/vue-cli
[3] webpack: https://webpack.js.org/
[4] Chrome Experiments: https://experiments.withgoogle.com/chrome

 

STAY TUNED!

 

BEHIND THE TRACKS OF iJS

JavaScript Practices & Tools

DevOps, Testing, Performance, Toolchain & SEO

Angular

Best-Practises with Angular

General Web Development

Broader web development topics

Node.js

All about Node.js

React

From Basic concepts to unidirectional data flows