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

(singke) #1
Large Application Patterns with Vuex Chapter 18

This way the euro amount is never in the state but always computed. Moreover, it is


centralized in the store, so we don't need to add anything to our components.


Now, it's easy to retrieve the two amounts from a template:


<template>
<div>
<h1>Balance</h1>
<ul>
<li>{{$store.state.bitcoin}}฿</li>
<li>{{$store.getters.euro}}€</li>
</ul>
</div>
</template>

Here, ฿ ; is the HTML entity for the Bitcoin symbol.


How it works...


Having a getter for derived data is always a good idea if we are not talking about input


data. A notable feature of getters we have not yet discussed is their ability to interact with
other getters and take an argument.


Accessing other getters

The second argument passed to a getter when called is the object that contains the other
getters:


getters: {
...
getCatPictures: state => state.pictures.filter(pic => isCat(pic))
getKittens: (state, getters) => {
return getters.getCatPictures().filter(cat => !isAdult(cat))
}
}

In our recipe, we could call the euro getter to have some more derived data, like roughly


how many houses we can buy with our Bitcoin given an average price of 150,000 euros:


const store = new Vuex.Store({
state: {
bitcoin: 600,
rate: 1000
},
Free download pdf