Search code examples
vue.jsvuex

Vuex - this.$store.commit or state.commit?


I'm new to Vue. Is there a right and wrong way to commit a change to state? Both of the below examples work, so I'm trying to understand why / when to use one over the other?

import state from "../store/index";

state.commit('someMutation', data);

And if state isn't imported, it works like this:

this.$store.commit("someMutation", data);

Solution

  • There's not necessarily a "wrong" way to change state, but taking the docs as a cue, using $store.commit or dispatching actions is the way to go when using from components.

    I always use actions since they can be async, typed in Typescript, and hide any complexity about state changes from my components.