State Management with Vuex Chapter 21
Mutations
A mutation is the only method in which the state of the store can be changed; this is done
by committing/dispatching an action, as seen earlier. Let's create a new file inside
src/store named mutations.js and add the following:
import * as types from './mutation-types';
export default {
[types.INCREMENT](state) {
state.count++;
},
[types.DECREMENT](state) {
state.count--;
},
[types.RESET](state) {
state.count = 0;
},
};
You'll note that once again, we're using our action types to define the method names; this is
possible with a new feature from ES2015+ named computed property names. Now, any
time that an action is committed/dispatched, the mutator will know how to handle this and
return a new state.
Getters
We can now commit actions and have these actions return a new version of the state. The
next step is to create getters so that we can return sliced parts of our state across our
application. Let's create a new file inside src/store named getters.js and add the
following:
export default {
count(state) {
return state.count;
},
};