Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Transitions and Animations Chapter 13

Getting ready


This recipe is a little advanced; I would suggest you complete some of the recipes in this
chapter if you are not very familiar with transitions in Vue. If you can complete the Adding


entering and leaving transitions for elements of a lists recipe without much difficulty, you are
good to go.


How to do it...


You will build a little game--a bus station simulator!


Whenever a bus--represented by its emoji--leaves the station, all the other buses will drive a


little ahead to take its place. Every bus is identified by a number, as you can see from the
Vue instance data:


new Vue({
el: '#app',
data: {
buses: [1,2,3,4,5],
nextBus: 6
}
})

Whenever a new bus arrives, it will have a progressive number assigned. We want a new


bus to leave or go every two seconds. We can achieve this by hooking a timer when our


component is mounted on screen. Immediately after data, write the following:


mounted () {
setInterval(() => {
const headOrTail = () => Math.random() > 0.5
if (headOrTail()) {
this.buses.push(this.nextBus)
this.nextBus += 1
} else {
this.buses.splice(0, 1)
}
}, 2000)
}

The HTML of our app will look like this:


<div id="app">
<h3>Bus station simulator</h3>
<transition-group tag="p" name="station">
<span v-for="bus in buses" :key="bus"> </span>
Free download pdf