In vue.js app, using vuex as state management store, I need to simply change the value of a property in vuex. For this I can follow two methods:
Dispatch an action
method, which will further commit mutation
, which eventually will change the state.
The second method is to commit the mutation
directly from the component and the mutation method will then change the state.
Currently, I'm using first method like this:
In Component:
this.$store.dispatch('updateNotice', 'This is some notice')
In Actions:
updateNotice ({state, getters, commit}, payload) { commit('UPDATE_NOTICE', payload) }
In Mutations:
UPDATE_NOTICE (state, payload) { state.notice = payload }
As you might have noticed, I'm using the action
method simply to commit a single mutation, without any other logic or async functionality.
My question is, in this case, should I not directly commit the mutation from the component itself? What is the best practice? Since using action
method in this simple case seems verbose and serve no specific purpose.
Is there any reason that I should always commit
actions from a component? Afterall, in vuex the ...mapMutations()
have some reason to exist.
To change another module state from one module in Vuex, we can call commit with the mutation name with the root option set to true . commit("TOGGLE_LOADING", null, { root: true }); to call commit to commit the TOGGLE_LOADING mutation with root set to true .
In Vuex, actions are functions that call mutations. Actions exist because mutations must be synchronous, whereas actions can be asynchronous. You can define actions by passing a POJO as the actions property to the Vuex store constructor as shown below. To "call" an action, you should use the Store#dispatch() function.
Mutations, as the name suggests is used to modify/mutate your state object. Actions are quite similar to mutations, but instead of mutating the state, Actions commit mutations. Actions can contain any arbitrary asynchronous code or business logic.
In your case it should be fine to commit the mutations directly in your components using ...mapMutations
or $store
instance.
Since you asked the best practice, The primary reason for the existence of Actions is Asynchronicity. Mutations cannot be asynchronous whereas Actions can be, while you can call $store.commit
directly in a Component this will be a synchronous event, but when you call dispatch
the commit can be handled asynchronously within the action block unlike Mutations.
So the best practice is to use Actions to commit modifications to your state when it has to be handled asynchronously say you need to do an API call before committing the state change in such cases it would be a good idea to use Actions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With