DEV Community

Jiří Procházka
Jiří Procházka

Posted on • Updated on

Vuex mixins

Wouldn't it be nice to have a possibility to use a Vuex setter in more modules?
That is what are mixins made for, right?

But you can't use Vue mixins in Vuex. Despite that, thanks to ES6 features it's easy to achieve that. We have a spread operator available.

// mixins.js
export const mixinState = () => {
  return {
    fields: []
  };
}


export const mixinMutations = () => {
  return {
    addField(state, field) {
      state.fields.push(field);
    }
  };
}
Enter fullscreen mode Exit fullscreen mode
// module.js
import { mixinMutations, mixinState } from "./mixins.js";

const state = mixinState; // replace whole state with the state defined in mixin

const mutations = {
  ...mixinMutations(), // merge mutations defined here with mixin mutations
  clearFields(state) {
    state.fields = [];
  }
};

const actions = {
  addField({ commit }, field) {
    commit("addField", field);
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
};

Enter fullscreen mode Exit fullscreen mode

And that's it. Such simple it is.

Vuex mixins vs. modules

Of course you can have objections that it is what modules are made for. That's true, but modules are good for more complex units of state (state, getters) and behaviour (actions, setters).

Vuex mixins are more for reusing simple things like structures stored in state and it's setters.
For example I have a deeply nested object which is fallen apart into several state fields after normalization and I want to use such fallen structure in more Vuex modules. And the setters doing such decomposition accordingly with it.

Top comments (0)