1

If actions are the only processes that manipulates store's values, can they do it directly or must they still always use mutations? Can an action set the value of a variable directly? There are no asynchronous events involved, just calculations.

Simple example:

actions: {
    resetToZero (state) {
    state.amount = 0
    state.display = ''
    state.color = black
    }
desertnaut
  • 57,590
  • 26
  • 140
  • 166
BryTack
  • 21
  • 5

1 Answers1

0

This is wrong "...actions are the only processes that manipulates store's values".

The only way to actually change state in a Vuex store is by committing a mutation.

Actions can commit mutations if needed:

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

We can also commit mutations from a component if needed:

this.$store.commit('increment')

To answer your question: Yes, you must always commit a mutation (use mutations) if a state/s has to be changed. With that being said, I don't think vuex will stop you from changing a state directly from actions, but that is not the best practice. Not even best practice, you are using the vuex store incorrectly. Plus you will lose the benefit of tracking where all the states are being changed (which is the reason why mutations exists).

Actions are solely used for business logic (calculations), async calls (actions don't have to contain async calls), and committing mutations (if needed). Mutations are solely used to change states (there should be no logic in mutations).

The example you gave, resetToZero has no logic and only changes states. This is incorrect use of vuex store. Thus, you need to move resetToZero to mutations. And anytime you need to resetToZero, you need to commit('resetToZero').

This post may help you out: Vuex Action vs Mutations

Leesa
  • 740
  • 2
  • 11
  • 15
  • if mutations are just function wrappers to mutate the state , why can't we just mutate the state directly without those mutations? – Konrad Aug 01 '19 at 14:57