Building your first Vue.js 2 Web application

0
3122
10 min read

Vue is a relative newcomer in the JavaScript frontend landscape, but a very serious challenger to the current leading libraries. It is simple, flexible, and very fast, while still providing a lot of features and optional tools that can help you build a modern web app efficiently. In today’s tutorial, we will explore Vue.js library and then we will start creating our first web app.

Why another frontend framework?

Its creator, Evan You, calls it the progressive framework.

  • Vue is incrementally adoptable, with a core library focused on user interfaces that you can use in existing projects
  • You can make small prototypes all the way up to large and sophisticated web applications
  • Vue is approachable– beginners can pick up the library easily, and confirmed developers can be productive very quickly

Vue roughly follows a Model-View-ViewModel architecture, which means the View (the user interface) and the Model (the data) are separated, with the ViewModel (Vue) being a mediator between the two. It handles the updates automatically and has been already optimized for you. Therefore, you don’t have to specify when a part of the View should update because Vue will choose the right way and time to do so.

The library also takes inspiration from other similar libraries such as React, Angular, and Polymer. The following is an overview of its core features:


  • A reactive data system that can update your user interface automatically, with a lightweight virtual-DOM engine and minimal optimization efforts, is required
  • Flexible View declaration–artist-friendly HTML templates, JSX (HTML inside JavaScript), or hyperscript render functions (pure JavaScript)
  • Composable user interfaces with maintainable and reusable components Official companion libraries that come with routing, state management, scaffolding, and more advanced features, making Vue a non-opinionated but fully fleshed out frontend framework

Vue.js – A trending project

Evan You started working on the first prototype of Vue in 2013, while working at Google, using Angular. The initial goal was to have all the cool features of Angular, such as data binding and data-driven DOM, but without the extra concepts that make a framework opinionated and heavy to learn and use.

The first public release was published on February 2014 and had immediate success the very first day, with HackerNews frontpage, /r/javascript at the top spot and 10k unique visits on the official website.

The first major version 1.0 was reached in October 2015, and by the end of that year, the npm downloads rocketed to 382k ytd, the GitHub repository received 11k stars, the official website had 363k unique visitors, and the popular PHP framework Laravel had picked Vue as its official frontend library instead of React.

The second major version, 2.0, was released in September 2016, with a new virtual DOM- based renderer and many new features such as server-side rendering and performance improvements. This is the version we will use in this article. It is now one of the fastest frontend libraries, outperforming even React according to a comparison refined with the React team. At the time of writing this article, Vue was the second most popular frontend library on GitHub with 72k stars, just behind React and ahead of Angular 1.

The next evolution of the library on the roadmap includes more integration with Vue-native libraries such as Weex and NativeScript to create native mobile apps with Vue, plus new features and improvements.

Today, Vue is used by many companies such as Microsoft, Adobe, Alibaba, Baidu, Xiaomi, Expedia, Nintendo, and GitLab.

Compatibility requirements

Vue doesn’t have any dependency and can be used in any ECMAScript 5 minimum- compliant browser. This means that it is not compatible with Internet Explorer 8 or less, because it needs relatively new JavaScript features such as Object.defineProperty, which can’t be polyfilled on older browsers.

In this article, we are writing code in JavaScript version ES2015 (formerly ES6), so you will need a modern browser to run the examples (such as Edge, Firefox, or Chrome). At some point, we will introduce a compiler called Babel that will help us make our code compatible with older browsers.

One-minute setup

Without further ado, let’s start creating our first Vue app with a very quick setup. Vue is flexible enough to be included in any web page with a simple script tag. Let’s create a very simple web page that includes the library, with a simple div element and another script tag:

<html>
<head>
<meta charset="utf-8">
<title>Vue Project Guide setup</title>
</head>
<body>
 
<!-- Include the library in the page -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
 
<!-- Some HTML -->
<div id="root">
<p>Is this an Hello world?</p>
</div>
 
 <!-- Some JavaScript →>
<script>
console.log('Yes! We are using Vue version', Vue.version)
</script>
 
</body>
</html>

In the browser console, we should have something like this:

Yes! We are using Vue version 2.0.3

As you can see in the preceding code, the library exposes a Vue object that contains all the features we need to use it. We are now ready to go.

Creating an app

For now, we don’t have any Vue app running on our web page. The whole library is based on Vue instances, which are the mediators between your View and your data. So, we need to create a new Vue instance to start our app:

// New Vue instance var app = new Vue({

// CSS selector of the root DOM element

el: '#root',

// Some data

data () { return {

message: 'Hello Vue.js!',

}

},

})

The Vue constructor is called with the new keyword to create a new instance. It has one argument–the option object. It can have multiple attributes (called options). For now, we are using only two of them.

With the el option, we tell Vue where to add (or “mount”) the instance on our web page using a CSS selector. In the example, our instance will use the <div id=”root”> DOM element as its root element. We could also use the $mount method of the Vue instance instead of the el option:

var app = new Vue({ data () {

return {

message: 'Hello Vue.js!',

}

},

})

// We add the instance to the page

app.$mount('#root')

Most of the special methods and attributes of a Vue instance start with a dollar character.

We will also initialize some data in the data option with a message property that contains a string. Now the Vue app is running, but it doesn’t do much, yet.

You can add as many Vue apps as you like on a single web page. Just create a new Vue instance for each of them and mount them on different DOM elements. This comes in handy when you want to integrate Vue in an existing project.

Vue devtools

An official debugger tool for Vue is available on Chrome as an extension called Vue.js devtools. It can help you see how your app is running to help you debug your code. You can download it from the Chrome Web Store (https://chrome.google.com/webstore/ search/vue) or from the Firefox addons registry (https://addons.mozilla.org/en-US/ firefox/addon/vue-js-devtools/?src=ss).

For the Chrome version, you need to set an additional setting. In the extension settings, enable Allow access to file URLs so that it can detect Vue on a web page opened from your local drive:

Vue.js

On your web page, open the Chrome Dev Tools with the F12 shortcut (or Shift + command + c on OS X) and search for the Vue tab (it may be hidden in the More tools… dropdown). Once it is opened, you can see a tree with our Vue instance named Root by convention. If you click on it, the sidebar displays the properties of the instance:

Vue.js Root

You can drag and drop the devtools tab to your liking. Don’t hesitate to place it among the first tabs, as it will be hidden in the page where Vue is not in development mode or is not running at all.

You can change the name of your instance with the name option:

var app = new Vue({

name: 'MyApp',

// ...

        })

This will help you see where your instance in the devtools is when you will have many more:

Vue.js My App

Templates make your DOM dynamic

With Vue, we have several systems at our disposal to write our View. For now, we will start with templates. A template is the easiest way to describe a View because it looks like HTML a lot, but with some extra syntax to make the DOM dynamically update very easily.

Displaying text

The first template feature we will see is the text interpolation, which is used to display dynamic text inside our web page. The text interpolation syntax is a pair of double curly braces containing a JavaScript expression of any kind. Its result will replace the interpolation when Vue will process the template. Replace the <div id=”root”> element with the following:

<div id="root">

<p>{{ message }}</p>

</div>

The template in this example has a <p> element whose content is the result of the message JavaScript expression. It will return the value of the message attribute of our instance. You should now have a new text displayed on your web page–Hello Vue.js!. It doesn’t seem like much, but Vue has done a lot of work for us here–we now have the DOM wired with our data.

To demonstrate this, open your browser console and change the app.message value and press Enter on the keyboard:

app.message = 'Awesome!'

The message has changed. This is called data-binding. It means that Vue is able to automatically update the DOM whenever your data changes without requiring anything from your part. The library includes a very powerful and efficient reactivity system that keeps track of all your data and is able to update what’s needed when something changes. All of this is very fast indeed.

Adding basic interactivity with directives

Let’s add some interactivity to our otherwise quite static app, for example, a text input that will allow the user to change the message displayed. We can do that in templates with special HTML attributes called directives.

All the directives in Vue start with v- and follow the kebab-case syntax. That means you should separate the words with a dash. Remember that HTML attributes are case insensitive (whether they are uppercase or lowercase doesn’t matter).

The directive we need here is v-model, which will bind the value of our <input> element with our message data property. Add a new <input> element with the v-model=”message” attribute inside the template:

<div id="root">

<p>{{ message }}</p>

<!-- New text input -->

<input v-model="message" />

</div>

Vue will now update the message property automatically when the input value changes. You can play with the content of the input to verify that the text updates as you type and the value in the devtools changes:

Vue.js

There are many more directives available in Vue, and you can even create your own.

To summarize, we quickly set up a web page to get started using Vue and wrote a simple app. We created a Vue instance to mount the Vue app on the page and wrote a template to make the DOM dynamic. Inside this template, we used a JavaScript expression to display text, thanks to text interpolations. Finally, we added some interactivity with an input element that we bound to our data with the v-model directive.

You read an excerpt from a book written by Guillaume Chau, titled Vue.js 2 Web Development Projects. Its a project-based, practical guide to get hands-on into Vue.js 2.5 development by building beautiful, functional and performant web.

Vue.js 2 Web Development Projects

Read Next

Why has Vue.js become so popular?

Building a real-time dashboard with Meteor and Vue.js

 

 

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here