This repository has been archived by the owner on Aug 8, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
56 lines (47 loc) · 1.69 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import clone from '@ianwalter/clone'
import { merge } from '@generates/merger'
export default function VuexReset (opts = {}) {
const { ssr, trigger } = merge({ trigger: 'reset' }, opts)
return store => {
// Extract the initial state from the store so that it can be used to reset
// the store when a trigger mutation is executed.
const initialState = clone(store.state)
// If the Vuex store needs to be hydrated from SSR data, add it to the store
// after the initialState is set so that initialState isn't polluted with
// SSR data and the store can be reset cleanly.
if (ssr) {
store.replaceState(merge(clone(store.state), clone(ssr)))
}
store.subscribe((mutation, state) => {
if (mutation.type === trigger) {
const newState = clone(initialState)
// Don't reset route module if set.
if (state.route) {
newState.route = clone(state.route)
}
// Reset the entire store state.
store.replaceState(newState)
} else {
// Extract the name of the module and mutation.
let mod = mutation.type.split('/')
const mut = mod.pop()
if (mut === trigger) {
// Reset the state for the module containing the mutation.
mod = mod.join('/')
store.replaceState({
...clone(state),
[mod]: clone(initialState[mod])
})
}
}
})
store.registerModuleState = (namespace, mod) => {
store.registerModule(namespace, mod)
initialState[namespace] = clone(mod.state)
}
store.unregisterModuleState = namespace => {
store.unregisterModule(namespace)
delete initialState[namespace]
}
}
}