Reset Vuex Module State

Huy Bui Dac
Vue.js Developers
Published in
1 min readJan 18, 2020

Vuex — the most powerful state management library in Vue.js ecosystem, but missing a small functionality that exists in most projects: “Reset all modules to its initial state”

Google

If you google by keyword: “vuex reset”, the results usually guide you in the following way:

  • For each module, declare a function that returns the initial state
  • For each module, declare a mutation that assigns the state by the initial value.

Refer: https://github.com/vuejs/vuex/issues/1118#issuecomment-356286218

And maybe, at least once, you’ve asked: “why clone it everywhere?”

Another approach

Vuex-Extensions is a tiny package to make your life easier.

Before vuex-extensions

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)export default new Vuex.Store({
plugins: [],
modules: {}
})

After vuex-extensions

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

Usage

In this case, reset the store in Vue component.

methods: {
handleLogout() {
this.$store.reset() // really easy
}
}

In this case, reset the store in Vuex action.

actions: {
logout() {
this.reset()
}
}

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

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

I hope this article was helpful for you. Thank you.

--

--