Vuex: one mutation to rule them all !?

published at 2019/10/25

Vue Vuex

Sometimes writing a mutation in vuex each time we want to edit some properties is tedious. That's why I generally prefer to use a generic mutation to handle that. Let me introduce it, in a few lines of code

// src/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import exampleModule from './example'

import {
} from 'lodash'


export default function () {
  const Store = new Vuex.Store({
    modules: {

    state: {

    getters: {

    mutations: {
      this is the generic mutation I talked about. Just as simple as that, thx to the set method of Lodash library.
      With that method, you can pass any object (with nested properties if you want) by using dot notation. More on that later
      mutate (state, payload) { 
        set(state,, payload.value)
    actions: {
    strict: process.env.DEV,

  return Store

The "mutate" method is the crucial one. I use it every time I need to assign some values in my store. Very useful. You can use it in actions from different modules. For example, in a Quasar project, you can call it like that:

// src/store/example/actions.js

export function someAction ({
}, payload) {
  return new Promise((resolve, reject) => {
    this._vm.$'/some-action', payload)
      .then(r => {
        commit('mutate', {
          property: '',
        }, {
          root: true // don't forget to pass this second argument when you want to call a root mutation
      .catch(e => {

There is some limitations though if you over use this method. It's true that's practical but that kind of methods lacks of readability. If your mutation is an important one for your project, I suggest writing a specific mutation. But most of the time, you'll probably have minor updates to do in your store. In that case, using a generic mutation is fine and will ease your productivity.

Liens utiles