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

Creating a dynamic and animated list


In Vue most data is reactive. In practice this means that if something is going to change in our view-model, we will see the results immediately. This is what lets you concentrate on the app itself, leaving aside all the drawing logic. In this recipe, we are also going to acknowledge some limitations of this system.

Getting Ready

To complete this recipe, you should know how to use basic data-binding (introduced in the very first recipe) and how to create lists (second recipe).

How to do it...

In the previous recipe we built a list for a countdown for a missile launch:

<div id="app"> 
  <ul> 
    <li v-for="n in countdown">{{n}}</li> 
    <li>launch missile!</li> 
  </ul> 
</div>
new Vue({
  el:'#app',
  data: {
    countdown: 
      [10,9,8,7,6,5,4,3,2,1]
  }
})

Wouldn't it be great if it was animated? We can tweak the JavaScript to add numbers to countdown as seconds pass:

  1. Copy the preceding code in the HTML and JavaScript sectors of JSFiddle, with the exception that we will fill the countdown ourselves, so set it to an empty array.

To get hold of the countdown variable we must pass the variable through the Vue instance itself.

  1. Assign the Vue instance to a variable for later reference:
        var vm = new Vue({
          el:'#app',
          data: {
            countdown: []
          }
        })

This way we can use vm to access the Vue instance.

  1. Initialize the countdown from 10:
        var counter = 10
  1. Set up a function that repeatedly adds the number of remaining seconds to the now empty countdown array:
        setInterval(function () { 
          if (counter > 0) { 
            vm.countdown.push(counter--) 
          } 
        }, 1000)

How it works...

What we are going to do is get a reference of the countdown array and fill it with decrementing numbers with the help of setInterval.

We are accessing countdown through the vm variable we set in the line vm.countdown.push(counter--), so our list will get updated every time we add a new number to the array.

This code is very simple, just note that we must use the push function to add elements to the array. Adding elements with the square brackets notation will not work:

vm.countdown[counter] = counter-- // this won't work

The array will get updated, but this way of assignment will skip Vue's reactive system due to how JavaScript is implemented.

There's more

Running the code now will add countdown numbers one at a time; great, but what about the final element launch missile? We want that to appear only at the end.

To do that here is a little hack we can do directly in HTML:

<ul> 
  <li v-for="n in countdown">{{n}}</li> 
  <li>{{ countdown.length === 10 ? 'launch missile!' : '...' }}</li> 
</ul>

This solution is not the best we can do; learn more in the recipe on v-show.

We just learned that we cannot add elements to a reactive array with the brackets notation if we want it to update in the view. This is true also for the modification of elements using brackets and for manually changing the length of the array:

vm.reactiveArray[index] = 'updated value' // won't affect the view 
vm.reactiveArray.length = 0 // nothing happens apparently

You can overcome this limitation using the splice method:

vm.reactiveArray.splice(index, 1, 'updated value') 
vm.reactiveArray.splice(0)