Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Vue.js Quick Start Guide

You're reading from   Vue.js Quick Start Guide Learn how to build amazing and complex reactive web applications easily using Vue.js

Arrow left icon
Product type Paperback
Published in Oct 2018
Publisher Packt
ISBN-13 9781789344103
Length 186 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Ajdin Imsirovic Ajdin Imsirovic
Author Profile Icon Ajdin Imsirovic
Ajdin Imsirovic
Arrow right icon
View More author details
Toc

Table of Contents (10) Chapters Close

Preface 1. Introducing Vue FREE CHAPTER 2. Basic Concepts of Vue 2 3. Working with Vue-CLI, Components, Props, and Slots 4. Filters and Mixins 5. Making Your Own Directives and Plugins 6. Transitions and Animations 7. Using Vuex 8. Using Nuxt.js and Vue-Router 9. Other Books You May Enjoy

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 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. 

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 -->
<div id="example-1">
<button v-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 the name key.

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
}
}
})
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.

You have been reading a chapter from
Vue.js Quick Start Guide
Published in: Oct 2018
Publisher: Packt
ISBN-13: 9781789344103
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image