Last active
February 27, 2018 06:35
-
-
Save laphilosophia/6e7060d355d69e170cf0ea961ec6ec93 to your computer and use it in GitHub Desktop.
vuex state reset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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