Option 0 (New Recommended)
Consider switching to Pinia, new official state manager for Vue.
Mutations do not exist any more. These can be converted to actions instead, or you can just assign directly to the store within your components (eg. userStore.firstName = 'FirstName'
)
Option 1 (Old Recommended)
Keep it this way.
Pros:
- Standard, well-documented.
- IDE support. You can easily find usages of some mutation across your project.
- Easy to add more logic when needed, e.g. age should be a positive number, etc...
Cons:
- Might look repetitive, so it is easier to skip some non-trivial mutation. However, this can partly be solved by convention to put all trivial to the end of the file\section, as soon as mutation stops to be non-trivial - move it to the top of the file\section.
Option 2
Use a universal mutation :
mutate(state, payload) {
state[payload.property] = payload.with;
}
and call it:
commit('mutate', {
property: <propertyNameHere>,
with: <valueGoesHere>
});
Pros:
- Clean mutation section, non-trivial mutations are visually distinct.
Cons:
- A little harder to find related mutations, e.g. some can have two or more spaces after
property:
- More writing for each mutation call.
- Not really compatible with a standard way, so you can end with non-trivial mutation with additional logic, but someone can miss it and use a unified mutation call.
Option 3
Use some code generator, e.g. Hygen
Pros:
- You have the same code as from Option 1, including IDE support and future extension.
- You can set it to add in all places by a single command line - to state, mutation, and action (if needed).
- With typescript you also need to change interface of the store, wich can also be done with the same command line.
Cons:
- Can be hard to set up.
- Need additional informing of new team members.
Option 4
Use some Vuex plugin with predefined mutations, e.g. this one
Pros:
- Minimal setup.
- Clean mutation section, non-trivial mutations are visually distinct.
Cons:
- Needs some knowledge about the plugin.
- A little harder to find related mutations
- Not really compatible with a standard way, so you can end with non-trivial mutation with additional logic, but someone can miss it and use a mutation call provided by a plugin.