Modifying State with Mutations
So far, you've seen how to read data from a Vuex store, both with direct access to state and by using getters. But to actually change the state of a store, Vuex supports the idea of mutations. Mutations are methods you define in your store that handle changing state. So, for example, instead of your component simply setting a new value in the state, your component will ask the store to perform a mutation, and the store handles that logic itself.
Here's a simple example:
state: { Â Â totalCats: 5, Â Â name:'Lindy' }, mutations: { Â Â newCat(state) { Â Â Â Â state.totalCats++; Â Â }, Â Â setName(state, name) { Â Â Â state.name = name; Â Â } }
In the preceding snippet, the store has two values in its state, totalCats
and name
. Two mutations exist to allow you to change these values. All mutations are passed a state object that gives you direct access...