To directly change state with Vue and Vuex, we should use mutations. Mutations are synchronous functions responsible for modifying the state in a Vuex store.
To directly change state using mutations, we:
- Define a mutation in our Vuex store.
- Commit the mutation from our Vue components.
For example, we write
// store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
counter: 0
},
mutations: {
increment(state) {
state.counter++;
},
decrement(state) {
state.counter--;
},
setCounter(state, value) {
state.counter = value;
}
}
});
export default store;
In our Vue component:
<template>
<div>
<p>Counter: {{ counter }}</p>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
<button @click="setCounter(0)">Reset</button>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
computed: {
...mapState(['counter'])
},
methods: {
...mapMutations(['increment', 'decrement', 'setCounter'])
}
};
</script>
In this example we have a Vuex store with a counter
state and mutations to increment, decrement, and set the counter.
In the Vue component, we use mapState
to map the counter
state from the Vuex store to a computed property.
We use mapMutations
to map the mutations from the Vuex store to methods in the component.
We can then call these methods directly from the component to modify the state in the Vuex store.
By using mutations, we ensure that state changes are tracked, debuggable, and predictable.
Vuex enforces the principle of a single state tree and mutations being the only way to change the state, which helps manage state changes in a large application.