Update after using the solution below a little more
So it turns out that if you use replaceState
with an empty object ( {}
), you end up blocking reactivity, as your states disappear. So basically you have to reset each property in state and then use store.replaceState(resetStateObject)
. For a store without modules, you would do something like:
let state = this.$store.state; let newState = {}; Object.keys(state).forEach(key => { newState[key] = null;
Update (from comments). What if I need to reset / define only one module and leave the rest as is?
If you do not want to reset all your modules, you can simply reset the modules you need and leave the other reset in their current state.
For example, let's say you have several modules, and you only want to return module a
to its initial state, using the method above ^, which we will call resetStateA
. Then you should clone the initial state (which includes all the modules before reset).
var currentState = deepClone(this.state)
where deepClone
is your deep clone method ( lodash has a good one ). This clone has the current state before reset. So let's rewrite this
var newState = Object.assign(currentState, { a: resetStateA });
and use this new state with replaceState
, which includes the current state of all your modules except module a
with its initial state:
this.$store.replaceState(newState);
Original solution
I found this convenient method in Vuex.store
. You can quickly and painlessly clear all states with replaceState
, for example:
store.replaceState({})
It works with a single repository or with modules and maintains the reactivity of all the properties of your state. See the Vuex api doc page and find the page for replaceState
.
For modules
If you replace the store with modules, you will need to include empty status objects for each module. So, for example, if you have modules a
and b
, you should do:
store.replaceState({ a: {}, b: {} })