DEV Community

loading...

Vuex mixins

jiprochazka profile image Jiří Procházka Updated on ・1 min read

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);
    }
  };
}
// 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
};

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.

Discussion

pic
Editor guide