Reputation: 9
In Vuex, what is the logic of having both "actions" and "mutations?"
I understand the logic of components not being able to modify state (which seems smart), but having both actions and mutations seems like you are writing one function to trigger another function, to then alter state.
What is the difference between "actions" and "mutations," how do they work together, and more so, I'm curious why the Vuex developers decided to do it this way?
I've tried .......
import Vuex from 'vuex'
const store = new Vuex.Store({
state: {
count: 1
},
mutations: {
INCREMENT (state) {
// mutate state
state.count++
}
}
})
Error code 502
Upvotes: 0
Views: 1155
Reputation: 53
Mutations Must Be Synchronous so there is no way to change the state in async operation.
To solve this problem, vuex provides actions that change the state by commiting the synchronous mutations
If you have sync operation just use mutation, otherwise action + mutation
Upvotes: 1
Reputation: 6878
Actions and mutations are similar in their behavior, so the differences are:
Example:
actions: {
MODIFY({dispatch, commit, getters, rootGetters}, obj) {
//Do something
commit('mymutation', obj)
}
}
mutations: {
mymutation(state, obj) {
store.state.count = 1
}
}
You can check more about mutations and actions at Vuex documentation
Upvotes: 1
Reputation: 2130
Upvotes: 1