Book Image

Vue.js 2 Cookbook

By : Andrea Passaglia
Book Image

Vue.js 2 Cookbook

By: Andrea Passaglia

Overview of this book

Vue.js is an open source JavaScript library for building modern, interactive web applications. With a rapidly growing community and a strong ecosystem, Vue.js makes developing complex single page applications a breeze. Its component-based approach, intuitive API, blazing fast core, and compact size make Vue.js a great solution to craft your next front-end application. From basic to advanced recipes, this book arms you with practical solutions to common tasks when building an application using Vue. We start off by exploring the fundamentals of Vue.js: its reactivity system, data-binding syntax, and component-based architecture through practical examples. After that, we delve into integrating Webpack and Babel to enhance your development workflow using single file components. Finally, we take an in-depth look at Vuex for state management and Vue Router to route in your single page applications, and integrate a variety of technologies ranging from Node.js to Electron, and Socket.io to Firebase and HorizonDB. This book will provide you with the best practices as determined by the Vue.js community.
Table of Contents (19 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Dedication
Preface

Writing lists


The desire to produce lists almost seems to be an innate part of human nature. There is a deeply satisfying feeling that one obtains by watching a well ordered list marching down the computer screen.

With Vue, we are given the tools to make lists of any kind with a stunning appearance and maximum ease.

Getting Ready

For this recipe we are going to use basic data-binding, if you follow the very first recipe you are already familiar with it.

How to do it...

We are going to build lists in a couple of different ways: with a range of numbers, with an array, and finally with an object.

Range of numbers

To start off with lists, set up your JSFiddle like in the preceding recipe, adding Vue.js as a framework. Select Vue 2.2.1 (or Vue (edge)):

  1. In the JavaScript section, write:
        new Vue({el:'#app'})

 

  1. And in the HTML write:
        <div id="app"> 
          <ul> 
            <li v-for="n in 4">Hello!</li> 
          </ul> 
        </div>

This will result in a list with Hello! written four times. In a few seconds your first list is complete, nice job!

We can write a countdown with this technique--in the HTML, replace the content of the <div> with the following:

<div id="app"> 
  <ul> 
    <li v-for="n in 10">{{11-n}}</li> 
    <li>launch missile!</li> 
  </ul> 
</div>

Arrays

  1. In the HTML, to achieve the same result, edit the list to reflect the following:
        <ul> 
            <li v-for="n in [10,9,8,7,6,5,4,3,2,1]">{{n}}</li> 
            <li>launch missile!</li> 
        </ul>

Although this list is identical to the previous one, we shouldn't put literal arrays in HTML markup.

  1. We're better off with a variable that contains the array. Edit the preceding code to match the following:
        <ul> 
          <li v-for="n in countdown">{{n}}</li> 
          <li>launch missile!</li> 
        </ul>

 

  1. Then put the array countdown in the JavaScript:
        new Vue({ 
          el:'#app', 
          data: { 
            countdown: [10,9,8,7,6,5,4,3,2,1] 
          } 
        })
Arrays with index notation

When enumerating an array, we also have access to the index, represented by the variable i in the following code:

  1. The HTML becomes:
        <div id="app"> 
          <ul> 
            <li v-for="(animal, i) in animals">
              The {{animal}} goes {{sounds[i]}}
            </li> 
          </ul> 
        </div>
  1. In the code part, write:
        new Vue({ 
          el: '#app', 
          data: { 
            animals: ['dog', 'cat', 'bird'], 
            sounds: ['woof', 'meow', 'tweet'] 
          } 
        })

Objects

The preceding example can be refactored to match animal names and their sounds so that an accidental misalignment of the index will not affect our list.

  1. The HTML becomes:
        <div id="app"> 
          <ul> 
            <li v-for="(sound, name) in animals"> 
              The {{name}} goes {{sound}} 
            </li> 
          </ul> 
        </div>
  1. And we need to create the animals object in the JavaScript:
        new Vue({ 
          el: '#app', 
          data: { 
            animals: { 
              dog: 'woof', cat: 'meow', bird: 'tweet' 
            } 
          } 
        })

How it works...

The workings of lists are quite simple; here is a little more explanation on the syntax.

Range of numbers

The variable n is in scope inside the <li> tag. To prove it to yourself, you can quickly build a countdown list as follows:

<ul> 
  <li v-for="n in 10">{{11 - n}}</li> 
  <li>launch missile!</li> 
</ul>

We write 11 instead of 10 because enumeration in Vue is 1-indexed; this means that n in 10 will start to count from 1, not from 0 like someone might expect, and go up to 10. If we want our countdown to start from 10, then we have to put 11. The last number will be 10, so we'll have 1 as the last number before the missile is launched.

What v-for="n in 10" does is call enumeration; specifically we are enumerating a range of numbers (1 to 10).

Arrays

Vue allows us to enumerate arrays too. The general syntax is as follows:

v-for="(element, index) in array"

As seen, the index and parenthesis can be omitted if all we want are the array elements.

This form of enumeration is guaranteed to be ordered. In other words, the ordered sequence of elements in the array will be the same you will see on the screen; this is not the case when enumerating objects.

 

Objects

The syntax is v-for="(value, property)" and if you want you can also squeeze in the index with v-for="(value, property, index)". The latter is not recommended though since, as already said, the order in which properties are enumerated is not fixed. In practice, in most browsers, the order is the same as the insertion order but this is not guaranteed.