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

Getting ready


This recipe is for you if you already have some Vuex knowledge and want to expand your
horizons.


How to do it...


Imagine that you are building a Bitcoin wallet. You want to give your users an overview of


their balance, and you want them to see how many Euros it corresponds to.
Create a new Webpack template with vue init webpack and npm install vuex.


Create a new src/store/index.js file and write the following inside it:


import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
state: {
bitcoin: 600,
rate: 1000,
euro: 600000
}
})

export default store

This code is prone to errors. The first error can be a miscalculation of the Euro amount if we


don't get the multiplication right. The second kind of error can be that we tell the user the
bitcoin and euro balance during a transaction, resulting in a stale and wrong amount for


one of the two.


To tackle these issues, we use getters:


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