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...