Vue.js Quick Start Guide

By Ajdin Imsirovic
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. Introducing Vue

About this book

Vue.js is the latest trending frontend framework. Simplicity, reactivity, and ?exibility are some of the key benefits that Vue offers to developers. This book will help you learn everything you need to know to build stunning reactive web apps with Vue.js 2 quickly and easily.

This book will take you through the Vue 2 framework. You will start by learning the different Vue installation options: CDN, NPM, and Vue CLI. Then we will look at the core concepts of Vue: templates and components – ways to modularize Vue code. You will learn how to utilize directives, which are Vue-specific HTML attributes with additional features. Also, you will see how Vue uses a streamlined approach to development, with reusable methods, computed properties, and watchers, and how it controls state with the help of its data option.

You will learn about the concepts of reactive programming in Vue, and how to understand communication between parent and child components. We will take a look at props and slots, working with CSS, filters, and mixins. We will also look at ways to add transitions and animations to Vue apps. Then you will extend Vue by building custom directives and your own plugins.

Finally, you will learn about Vuex – a Vue plugin that allows us to centralize state, and also introduce Nuxt, which is a framework that builds on top of Vue and solves some issues of single-page applications. After learning about these components, you will be ready to build your own reactive web apps with Vue.js 2.

Publication date:
October 2018
Publisher
Packt
Pages
186
ISBN
9781789344103

 

Chapter 1. Introducing Vue

In this chapter, we will look into how to start learning Vue 2. This chapter will show you the easiest way to get started quickly and how to keep track of your progress easily with the help of the available SaaS platforms.

We will also look at why Vue is getting so popular, and why we should use it.

Furthermore, we'll discuss the basic building blocks of Vue: mustache templates, directives, modifiers, methods, and computed properties.

Along the way, we will look at a number of practical examples. Let's begin by looking at just what exactly Vue is.

In this chapter, we will take a look at the following topics:

  • What is Vue?
  • What problems does Vue solve?
  • Why use Vue?
 

What is Vue?


Vue is a simple and easy-to-use JS framework which appeared in 2013. It is the successful result of taking some excellent ideas from Angular and React and combining them in an easy-to-use package. 

Compared with other popular frontend frameworks, Vue comes out on top for simplicity and ease of use.

Let's see how we can start using it.

The quickest way to start using Vue2

In the last decade, a lot of the tools for web development have moved to the web, so let's go with the flow and start a new pen on http://codepen.io/.

Note

You don't have to be a member of https://codepen.io/ to create pens there—you can just save them with the blanket username Captain Anonymous. However, it's better to open an account so you have all your experiments in one place.

Once you navigate your browser to https://codepen.io, you'll be greeted with the following screen:

Click on the Create dropdown (in the main navigation, in the top-right area of the screen), and then click New Pen. Once you do, you will see the default editor setup:

Next, click the Settings button in the top right of the screen, and in the popup that appears choose JavaScript:

Next, in the Quick-add drop-down field, select the Vue option. Once you do, the first input will be filled out with the current minified version of Vue which is served from the Cloudflare CDN, or, more specifically, from this link: https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js.

That's it! We're ready to start using Vue2 in our Codepen project.

One thing to understand about Vue is that it makes our HTML dynamic. This is achieved by addingmustache syntax. This syntax is very easy to understand. We simply insert it inside an HTML element. For example, we can add mustache syntax to an h1 tag like this:

<h1>{{ heading1 }}</h1>

So, let's go over how this works in detail. Feel free to work on your own pen or see the example here: https://codepen.io/AjdinImsirovic/pen/rKYyvE.

Mustache template example

Let's begin working with our first pen:

<div id="entryPoint">
  <h1>Just an h1 heading here</h1>
  <h2>Just an h2 heading here</h2>
  <p>Vue JS is fun</p>
</div>

We can now see our HTML being rendered in the CodePen preview pane, with the following text printed on the screen:

Just an h1 heading here
Just an h2 heading here
Vue JS is fun

Note

Note that the CodePen app will often update the preview pane even without saving, which is a lot better than refreshing the browser—that must be done when working on your projects locally. Still, it is good to save your CodePen projects often, to not lose any changes (in the odd case of your browser freezing or something else out of the ordinary happening).

Next, let's add the following Vue code to the JS pane inside our pen:

new Vue({
  el: '#entryPoint',
  data: {
     heading1: 'Just an h1 heading here',
     heading2: 'heading 2 here',
     paragraph1: 'Vue JS'
  }
})

Finally, let's update the HTML so that the Vue code can work its magic:

<div id="entryPoint">
  <h1>{{ heading1 }}</h1>
  <h2>Just an {{ heading2 }}</h2>
  <p>{{paragraph1}} is fun</p>
</div>

In the previous code example, we can see how we use mustache templates to dynamically insert data into our HTML.

Note

Mustache templating is achieved by simply passing the keys of our data object into our HTML tags and surrounding the keys with the opening {{ and closing }} tags.

As mentioned before, CodePen will auto-update the preview pane, but this will not affect the preview since we are effectively producing the same output as we did when we were using just plain HTML.

Now we can play with it simply by changing the key-value pairs inside our data entry:

new Vue({
  el: '#entryPoint',
  data: {
     heading1: 'This is an h1',
     heading2: 'h2 heading',
     paragraph1: 'Vue2'
  }
})

This time, the output will auto-update to this:

This is an h1 Just an h2 heading Vue2 is fun

We can also change our entry point. For example, we can have Vue access only the p tag:

new Vue({
  el: 'p',
  data: {
     heading1: 'This is an h1',
     //heading2: 'h2 heading',
     paragraph1: 'Vue2'
  }
})

After this change, our preview pane will show the following:

{{ heading1 }} Just an {{ heading2 }} Vue2 is fun

From this output, we can conclude that our mustache templates will be rendered in our HTML output as regular text if either of the following things happen:

  • Our entry point does not reference the data
  • The entry in our data does not exist

We've also seen how our entry point can be any kind of selector. You can think of it as being similar to how you can target different elements in jQuery.

For example, we could have a more complex selector as our app's entry point:

new Vue({
  el: 'div#entryPoint',
  data: {
     heading1: 'This is an h1',
     heading2: 'h2 heading',
     paragraph1: 'Vue2'
  }
})

Using Vue's data option as a function

Note that the data option of our Vue instance can be either an object or a function. An example of data as an object can be seen in the previous code. Using data as a function is easy as well.

Note

Data as an object doesn't work well with reusable components. For this reason, using data as a function is, generally speaking, a more useful way to use the data option in Vue.

Let's see another pen. This time, we'll use the data option as a function, instead of as an object. The pen is available here: https://codepen.io/AjdinImsirovic/pen/aKVJgd. The only change we'll make is in our Vue code:

new Vue({
  el: '#entryPoint',
  data() {
    return {
     heading1: 'Just an h1 heading here',
     heading2: 'heading 2 here',
     paragraph1: 'Vue JS data as a function'
    }
  }
})

Now that we're familiar with the very basics of Vue syntax, let's look at what it can be used for.

 

What problems does Vue solve?


Without trying to make an extensive list, let's quickly highlight some of Vue's greatest strengths:

  • Vue—a jQuery successor?
  • Vue is a great learning tool for beginners
  • Vue is a versatile and progressive framework
  • Vue is an awesome tool for animations and interactions
  • Vue's approach is similar to other modern frontend frameworks and libraries

Next, let's briefly go over each of these points.

Vue, a jQuery successor

The famous jQuery library appeared in 2006. When it came out, it did a few things beautifully:

  • It made writing cross-browser JavaScript a lot easier, which was a big plus at the time since it dramatically decreased the need for developers to mess with various browsers' quirks and inconsistencies
  • It had a simple syntax that made it easier to target and manipulate specific DOM nodes, which is beautifully phrased in their motto write less, do more
  • It was an excellent entry point to learning JavaScript in general
  • It had a great API that made working with Ajax simple and easy

However, a lot has changed since then—for the better.

Arguably, the biggest improvement that happened in JavaScript-land between 2006 and today is the virtual DOM. 

Note

The virtual DOM was a paradigm shift: we no longer had to write procedural, spaghetti JS to instruct the browser on how to traverse and manipulate the DOM. Instead of telling the browser how to update the DOM, we can now simply tell it what to update. Or, to be more specific, we tell a framework what to update—a framework like View or React. The actual implementation of the virtual DOM is framework-specific and not really something to be concerned with at this point.

We can now work with the DOM indirectly, by using declarative code that deals with the virtual DOM implementation of the underlying framework. This abstraction is the one thing that more or less made jQuery redundant.

Of course, since so many apps are still powered by jQuery and since legacy code has a tendency to stick around, jQuery will be alive and well in the years to come. 

However, the paradigm shift in the way we think about DOM manipulation makes Vue a strong contender to jQuery's throne as the most popular game in town.

Vue also has other advantages: it is an excellent starting point to learn present-day frontend development. The barrier to entry is really low.

A learning tool for beginners

If a jQuery developer was faced with the option of learning either of the modern frontend frameworks/libraries, React, Angular, Vue, Ember... which one would probably be the easiest to get started with?

Vue, of course!

As we've seen already, getting started with Vue can be as simple as importing a CDN. And since we humans are wired to thrive on small, frequent victories, Vue seems to be the happy route to take. This is not to say that a developer should not try to learn other frontend frameworks too. It just seems that Vue is the easiest way to get started and the best way to get productive quickly.

A versatile and progressive framework

The official website for Vue JS says that Vue is the Progressive JavaScript Framework. This means you can add Vue to an existing server-side project incrementally. Basically, you can add Vue to just one simple section of your website. No wonder Laravel chose to bundle with Vue on its frontend.

But you don't have to settle for only sprinkling Vue in here and there. You can also extend it using Vuex and Vue-Router. This makes Vue very versatile and usable in a number of different scenarios.

A tool for animations and transitions

If you need to make high-performance animations and transitions, look no further than Vue! Vue's animations API is very easy to understand and it's a joy to use. It is so easy to do animations in Vue that you will be amazed at how much you can accomplish in a very short time.

Features similar to other modern frontend frameworks and libraries

Just like other modern frontend frameworks, such as React and Angular, Vue has the following:

  • Virtual DOM
  • A command-line interface (Vue-cli)
  • State management (Vuex)
  • Routing (Vue-Router)

However, it seems that Vue's core team is going out of their way to make Vue as approachable as possible. This is evident in several examples:

  • The effort they've put in to avoid the hassle of setting up Vue-cli, which makes it very easy to get started with 
  • The lack of complicated toolchains
  • The simplicity of Vue's API

Like the official project's website states, Vue is approachable, versatile, and performant.

 

Why use Vue?


We have discussed the problems that Vue solves in the previous section. In this section, we will look at practical examples of why it is a pleasure to work with:

  • Declarative code (we tell Vue what to do, not how to do it)
  • Easy to understand syntax (it's as minimal as it can get)
  • Feels like a right fit for a variety of projects

Declarative code

Let's compare vanilla JavaScript code with Vue JavaScript code.

For this example, we'll print out members of an array.

In vanilla JavaScript, this will be the code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    .list-item {
      background: white;
      color: gray;
      padding: 20px;
      margin: 20px;
    }
  </style>
</head>
<body>

  <script>
    var arr1 = ['a','b','c'];
    var unorderedList = document.createElement('ul');
    unorderedList.style.cssText = "background:tomato; width: 
    400px;height:400px";
    document.body.appendChild(unorderedList);
    for (var i=0; i<3; i++) {
      var listItem = document.createElement('li');
      listItem.className = "list-item";
      unorderedList.appendChild(listItem);
      listItem.innerHTML = arr1[i];
    }
  </script>
</body>
</html>

In this file, the focus should be on the code inside the script tags.

You can see this example in the form of a pen at this URL: https://codepen.io/AjdinImsirovic/pen/xzPdxO.

There are several things that we are doing in this code:

  1. We are setting array1, which will later populate the list items we will create dynamically
  2. We are creating a ul—an unordered list element that will wrap all our list items (all our li elements)
  3. We are setting the styles for our ul
  1. We are appending unorderedList to the body of our document
  2. Next, we use a for loop to create three li elements
  3. Still inside the for loop, we add a class to each list item
  4. We then append each of them to the unordered list element
  5. Finally, we add innerHTML to each list item 

Many objections could be made to the way that this code is made. We could have used a forEach; we could have avoided adding styles the way we did and instead called the CSS from a separate file. But the biggest objection is how fragile this code is. Let's contrast this code with the same thing written in Vue.

In Vue, our code will look like this:

<!-- HTML -->
<ul>
  <li v-for="entry in entries">
     {{ entry.content }}
  </li>
</ul>

// JS
var listExample = new Vue ({
  el: "ul",
  data: {
    entries: [
      { content: 'a'},
      { content: 'b'},
      { content: 'c'}
    ]
  }
})

The code for this example can be found here: https://codepen.io/AjdinImsirovic/pen/VdrbYW.

As we can see at just a simple glance, Vue's code is a lot easier to understand and reason about in comparison to the same code implemented in vanilla JavaScript. 

Note

The el here is the entry point for our Vue app. The data option is the actual data our Vue app will work with. 

There's also another major benefit to this setup: once you understand how Vue works, any other project that uses Vue will simply make sense to you, which will yield increased productivity and efficiency.

The Vue way of doing things thus promotes being faster and doing more things in less time.

Feels like a right fit for a variety of projects

One of the strengths of Vue is the possibility of incremental implementation. If you would just like to make a quick, simple experiment in Vue, no problems. You can start with Vue in under a minute, literally. 

This makes it great for converting legacy projects, building projects from scratch, or for simple experiments.

Vue is also maturing quickly. There is a vibrant Vue community and a lot of developers are working on it continuously. For example, one of the arguments for people to choose React over Vue was the lack of a framework to build native mobile apps in Vue. That's no longer the case: Vue Native is available as of June 2018. You can check it out at https://github.com/GeekyAnts/vue-native-core, or find out more about it at https://vue-native.io/.

With all of this in mind, there are plenty of reasons why learning Vue is a nice return on investment for anyone, especially frontend developers. 

Easy-to-understand syntax

One thing that can be noticed in this example of a very simple Vue app is the use of the v-for HTML attribute. 

Directives

All the v-* attributes in Vue are called directives, which is borrowed from Angular.

The concept of directives is very interesting. They make code easier to understand, easier to think about, and easier to work with.

There are other directives in Vue that we will use extensively throughout this book. For now, let's just list some of them: v-bind, v-cloak, v-for, v-else, v-else-if, v-model, v-on, v-oncev-text, and v-html.

An example of a useful directive is v-model. The v-model directive is used to make forms reactive; it helps us update data on user input events. While this topic might sound a bit advanced to a beginner in Vue, this complexity is dealt with so elegantly that even beginners should find it easy to see what is happening in the code:

<!-- HTML -->
<div id="app">
  <span>Enter the weight in kilograms:</span>
  <input v-model="someNum" type="number">
  <div>The weight in pounds is: {{ someNum * 2.20 }}</div>
</div>

// js
new Vue({
  el: '#app',
  data() {
    return {
      someNum: "1"
    }
  }
})

As you can see, the {{ someNum }} value is bound to whatever a user types into the input field. In other words, the underlying data model—the value of someNum—will change based on user input.

To view the pen for the preceding example, visit https://codepen.io/AjdinImsirovic/pen/pKdPgX.

Modifiers

The directives in Vue are further extended with the help of modifiers.

The link to official documentation on modifiers in directives can be found at this link: https://vuejs.org/v2/guide/forms.html#Modifiers.

To use a modifier, we simply append it to a directive. The simplest possible example might look a bit like this:

<!-- HTML -->
<div>
  <input v-model.trim="userInput" placeholder="type here">
  <p>You have typed in: {{ userInput }}</p>
</div>

// js
new Vue({
  el: 'div',
  data() {
    return {
      userInput: ""
    }
  }
})

We have just appended the trim modifier to the v-model directive.

You can view the example for this code at this link: https://codepen.io/AjdinImsirovic/pen/eKeRXK.

This modifier will trim any whitespace (such as spaces or tabs) typed into the input field by the user.

Before continuing with this 10,000-foot overview of Vue syntax, let's also mention the v-on directive, which is used for event handling. Here is a quick example:

<!-- HTML -->
<divid="example-1">
<buttonv-on:click="counter += 1">Add 1</button>
<p>The button above has been clicked {{ counter }} times.</p>
</div>

// JS
var example1 = new Vue({
  el: '#example-1',
  data: {
    counter: 0
  }
})

Vue even provides shortcut syntax for v-on: the @ symbol. Thus, we can replace v-on:click with just @click and our Vue counter will still work.

To view this example in http://codepen.io/, visit the following URL: https://codepen.io/AjdinImsirovic/pen/PaOjvz.

Vue methods

The methods option in a Vue instance just lists all the functions that exist on that Vue instance (or on a Vue component).

The methods option works with the data of the Vue instance. What follows is a simple demonstration of this concept in practice:

// HTML
<div id="definitions">
  <!-- 'whatIsVue' and 'whyUseVue' are functions defined in the 'methods' option in the Vue instance -->
  <button id="btn" v-on:click="whatIsVue">What is Vue?</button>
  <button id="btn" v-on:click="whyUseVue">Why use Vue?</button>
</div>

// JS
var definitions = new Vue({
 el: '#definitions',
 data: {
 name: 'Vue.js'
 },
 // define methods (functions) under the `methods` object
 methods: {
   whatIsVue: function () {
    console.info(this.name + ' is a Progressive Front-end Framework')
   },
   whyUseVue: function () {
    alert('Because ' + this.name + ' is nice.')
   }
 }
})

As we can see, the data option holds the Vue.js string, which can be accessed via thenamekey.

Inside the methods option, we can see two functions: whatIsVue and whyUseVue. The whatIsVue function takes the click event and logs out the value inside name to the console. The whyUseVue function inside the methods option works similarly. 

This code can be seen in a pen at this address: https://codepen.io/AjdinImsirovic/pen/yEPXdK.

Computed properties and watchers

Computed properties are used to avoid complex logic adding bloat to your views. In other words, computed properties are useful to hide the complexity from our HTML and thus keep our HTML understandable, easy to use, and declarative. Put differently, when we need to compute some values from the data option, we can do that with the help of computed properties.

The full code for the following example can be seen at https://codepen.io/AjdinImsirovic/pen/WyXEOz:

<!-- HTML -->
<div id="example">
  <p>User name: "{{ message }}"</p>
  <p>Message prefixed with a title: "{{ prefixedMessage }}"</p>
</div>

// JS
var example = new Vue({
  el: '#example',
  data: {
    userName: 'John Doe',
    title: ''
  },
  computed: {
    // a computed getter
    prefixedMessage: function () {
      // `this` points to the Vue instance's data option
      return this.title + " " + this.userName
    }
  }
})

Note

Computed properties are cached. As long as a computed property's dependencies do not change, Vue will return the cached value of the computed property.

Watchers are not as frequently used as computed properties are. In other words, the watch option is to be used less frequently than the computed properties option. Watchers are commonly used for asynchronous or otherwise costly operations with changing data.

Watchers have to do with reactive programming; they allow us to observe a sequence of events through time and react to changes as they happen on a certain data property. 

We will cover the subject of computed properties and watchers in later chapters. For now, it is sufficient to know that they exist in Vue and that they are widely used.

 

Summary


In this chapter, we looked at how to get started with Vue quickly, with the help of codepen.io. We also discussed some of the most important ideas and concepts in Vue, such as the quickest and most developer-friendly way to start learning Vue 2. We looked into what problems Vue solves, what its strengths are, and why it is sometimes referred to as the new jQuery. We learned about mustache templates, Vue's declarative code, and its easy-to-understand syntax. Finally, we introduced directives, modifiers, methods, computed properties, and watchers.

In the next chapter, we will see what reactive programming is and how it is applied in Vue. We will also look at further expanding the concepts covered in this chapter, and we will introduce some additional features of Vue.

About the Author

  • Ajdin Imsirovic

    Ajdin Imsirovic is a full-stack web developer who has published several courses on the subject of web design and web development. He has also authored three books, Bootstrap 4 Cookbook, Elm Web Development, and Vue.js Quick Start Guide. In his fourth book, Vue CLI 3 Quick Start Guide, he introduces readers to the rich ecosystem of frontend tooling and best practices.

    Browse publications by this author
Vue.js Quick Start Guide
Unlock this book and the full library for FREE
Start free trial