Vuex: one mutation to rule them all !?

publié le 25/10/2019

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 {
  set
} from 'lodash'

Vue.use(Vuex)

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

    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.property, 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 ({
  commit
}, payload) {
  return new Promise((resolve, reject) => {
    this._vm.$axios.post('/some-action', payload)
      .then(r => {
        commit('mutate', {
          property: 'whatever.object.you.have',
          value: r.data
        }, {
          root: true // don't forget to pass this second argument when you want to call a root mutation
        })
        resolve(r)
      })
      .catch(e => {
        reject(e.response)
      })
  })
}


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