How to implement Mixins in Vuex

Huy Bui Dac
2 min readFeb 2, 2020

--

Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.
From: Vue.js

Vuex

Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.

In Vuex Core Concepts, Mutations are only way to actually change state in a Vuex store. And, you often see below duplicate code in most projects:

There are many ways to reduce the duplicate. The article is a example, they replaced them all with a single mutation:

const mutations = {
mutate(state, payload) {
state[payload.property] = payload.with;
}
};

If an action needs to store data in state, we call this mutation like this:

commit('mutate', {
property: <propertyNameHere>,
with: <valueGoesHere>
});

However, if you are on a very large project with lots of modules, you need to rewrite it on all modules.

Mixins are popular techniques for that, but Vuex doesn’t offer this feature.

Mixins for Vuex

Vuex-Extensions is a tiny package which brings Mixins feature into Vuex.

First, let vuex-extensions expand the original store by:

import Vue from 'vue'
import Vuex from 'vuex'
import { createStore } from 'vuex-extensions'
Vue.use(Vuex)export default createStore(Vuex.Store, {
plugins: [],
modules: {
moduleA,
moduleB
},
mixins: {} // magical here
}

Mixins object can contain getters/mutations/actions options. We create a mixin mutation which can be incorporated into all modules.

createStore(Vuex.Store, {
...
mixins: {
mutations: {
changeState: function (state, changed) {
Object.entries(changed)
.forEach(([name, value]) => {
state[name] = value
})
}
}
}
}

When you need to store data in state, we call this mutation like this:

commit('changeState', {
[propertyNameHere]: <propertyValueHere>
});

Our implementation will look like this:

Conclusion

In addition to mixin mutation, Vuex-Extensions also supports mixin getter and mixin action. By writing such common components, you can save your time and make some awesome codes.

Example: https://codesandbox.io/s/lively-thunder-hrh2o

Vuex-Extensions Repo: https://github.com/huybuidac/vuex-extensions

My other article for Vuex-Extensions, you might like to read:

--

--