Skip to content

Commit 676e5e5

Browse files
author
Guillaume Chau
committed
fix(vuex): dynamic modules with preserve state, closes #923
1 parent 7bf9bad commit 676e5e5

File tree

1 file changed

+30
-8
lines changed

1 file changed

+30
-8
lines changed

src/backend/vuex.js

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -52,11 +52,23 @@ export function initVuexBackend (hook, bridge, isLegacy) {
5252
function addModule (path, module, options) {
5353
if (typeof path === 'string') path = [path]
5454

55+
let state
56+
if (options && options.preserveState) {
57+
state = get(store.state, path)
58+
}
59+
if (!state) {
60+
state = typeof module.state === 'function' ? module.state() : module.state
61+
}
62+
5563
const key = path.join('/')
5664
registeredModules[key] = allTimeModules[key] = {
5765
path,
5866
module,
59-
options
67+
options: {
68+
...options,
69+
preserveState: false
70+
},
71+
state: stringify(state)
6072
}
6173

6274
if (SharedData.recordVuex) {
@@ -250,9 +262,13 @@ export function initVuexBackend (hook, bridge, isLegacy) {
250262
for (let i = stateSnapshot.index + 1; i <= index; i++) {
251263
const mutation = mutations[i]
252264
if (mutation.registerModule) {
253-
const { path, module, options } = mutation.payload
254-
tempAddedModules.push(path.join('/'))
255-
origRegisterModule(path, module, options)
265+
const key = mutation.payload.path.join('/')
266+
const registeredModule = registeredModules[key]
267+
tempAddedModules.push(key)
268+
origRegisterModule(registeredModule.path, {
269+
...registeredModule.module,
270+
state: parse(registeredModule.state, true)
271+
}, registeredModule.options)
256272
updateSnapshotsVm(store.state)
257273
} else if (mutation.unregisterModule && get(store.state, mutation.payload.path) != null) {
258274
const path = mutation.payload.path
@@ -296,8 +312,11 @@ export function initVuexBackend (hook, bridge, isLegacy) {
296312
origUnregisterModule(m.split('/'))
297313
})
298314
tempRemovedModules.sort((a, b) => a.length - b.length).forEach(m => {
299-
const { path, module, options } = registeredModules[m]
300-
origRegisterModule(path, module, options)
315+
const { path, module, options, state } = registeredModules[m]
316+
origRegisterModule(path, {
317+
...module,
318+
state: parse(state, true)
319+
}, options)
301320
})
302321
store._vm = originalVm
303322

@@ -356,8 +375,11 @@ export function initVuexBackend (hook, bridge, isLegacy) {
356375
if (!Object.keys(registeredModules).sort((a, b) => a.length - b.length).includes(m)) {
357376
const data = allTimeModules[m]
358377
if (data) {
359-
const { path, module, options } = data
360-
origRegisterModule(path, module, options)
378+
const { path, module, options, state } = data
379+
origRegisterModule(path, {
380+
...module,
381+
state: parse(state, true)
382+
}, options)
361383
registeredModules[path.join('/')] = data
362384
}
363385
}

0 commit comments

Comments
 (0)