Vue Answers

How directly change state with Vue Vuex?

Spread the love

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:

  1. Define a mutation in our Vuex store.
  2. Commit the mutation from our Vue components.

For example, we write

// store.js
import Vue from 'vue';
import Vuex from 'vuex';


const store = new Vuex.Store({
  state: {
    counter: 0
  mutations: {
    increment(state) {
    decrement(state) {
    setCounter(state, value) {
      state.counter = value;

export default store;

In our Vue component:

    <p>Counter: {{ counter }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
    <button @click="setCounter(0)">Reset</button>

import { mapState, mapMutations } from 'vuex';

export default {
  computed: {
  methods: {
    ...mapMutations(['increment', 'decrement', 'setCounter'])

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *