When building large applications such as Single Page Apps (SPA's), which typically consist of many reusable components they can quickly become difficult to build and maintain. The sharing of data and state between these components can also quickly break down and become difficult to debug and maintain.
By using a centralised application data store the entire application state can be represented in one place making the application more organised. Through the use of a unidirectional data flow, mutations and by scoping component data access to only the data required it becomes much simpler to reason about the component role and how it should affect the application state.
VueJS components are separate entities and they cannot share data between each other easily. To share data without vuex we need to emit
event with data and then listen and catch that event with on
.
component 1
this.$emit('eventWithDataObject', dataObject)
component 2
this.$on('eventWithDataObject', function (dataObject) {
console.log(dataObject)
})
With vuex installed we can simply access its data from any component without a need of listening to events.
this.$store.state.myData
We can also change data synchronously with mutators, use asynchronous actions and get data with getter functions.
Getter functions might work as global computed functions. We can access them from components:
this.$store.getters.myGetter
Actions are global methods. We can dispatch them from components:
this.$store.dispatch('myAction', myDataObject)
And mutations are the only way to change data in vuex.We can commit changes:
this.$store.commit('myMutation', myDataObject)
Vuex code would look like this
state: {
myData: {
key: 'val'
}
},
getters: {
myGetter: state => {
return state.myData.key.length
}
},
actions: {
myAction ({ commit }, myDataObject) {
setTimeout(() => {
commit('myMutation', myDataObject)
}, 2000)
}
},
mutations: {
myMutation (state, myDataObject) {
state.myData = myDataObject
}
}