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

In a mutation, it makes sense to have access only to the local state. The brain, for example,


cannot change the heart and vice versa, but what about actions? If we declare an action
inside a module, we are passed an object called context that looks like this:


{
"getters":{},
"state":{
"reason":true
},
"rootGetters":{},
"rootState":{
"brain":{
"left":{
"reason":true
},
"right":{
"fantasy":false
}
},
"heart":{
"loves": "Johnny Toast"
}
}
}

So, if we want to declare an action in the left lobe and we want to affect the heart, we have


to do something like the following:


actions: {
beNerd ({ rootState }) {
rootState.heart.loves = 'Math & Physics'
}
}

Building getters to help retrieve your data


You don't want to keep too much data in your state. It can be especially dangerous to keep


duplicate or derivative data because it can be brought out of sync very easily. Getters help
you with this without shifting the burden onto the components by keeping all the logic in


one place.

Free download pdf