Skip to content

Instantly share code, notes, and snippets.

@laphilosophia
Last active February 27, 2018 06:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laphilosophia/6e7060d355d69e170cf0ea961ec6ec93 to your computer and use it in GitHub Desktop.
Save laphilosophia/6e7060d355d69e170cf0ea961ec6ec93 to your computer and use it in GitHub Desktop.
vuex state reset
export const RESET_STATES = 'resetStates'
function resetState (state, moduleState) {
const mState = state[moduleState]
if (mState.initState && typeof mState.initState === 'function') {
const initState = mState.initState()
for (const key in initState) {
mState[key] = initState[key]
}
}
}
export const state = () => { /* ... */ }
export const mutations = {
[RESET_STATES]: (state, payload) => {
console.time('reset_states_time')
for (const moduleState in state) {
resetState(state, moduleState)
}
console.timeEnd('reset_states_time')
}
}
export const actions = {
async resetStates (context, payLoad) {
await context.commit(RESET_STATES, payLoad)
}
}
/*
@usage: whatever.vue
import { mapState, mapActions } from 'vuex'
<script>
methods: {
...mapActions({
resetStates: "resetStates"
})
},
watch: {
'$route' (to, from) {
this.resetStates()
}
}
</script>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment