Skip to content

Commit a86bd2d

Browse files
committed
document module reuse
1 parent f8b9eda commit a86bd2d

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

docs/en/modules.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,3 +243,25 @@ The module's state will be exposed as `store.state.myModule` and `store.state.ne
243243
Dynamic module registration makes it possible for other Vue plugins to also leverage Vuex for state management by attaching a module to the application's store. For example, the [`vuex-router-sync`](https://github.com/vuejs/vuex-router-sync) library integrates vue-router with vuex by managing the application's route state in a dynamically attached module.
244244

245245
You can also remove a dynamically registered module with `store.unregisterModule(moduleName)`. Note you cannot remove static modules (declared at store creation) with this method.
246+
247+
### Module Reuse
248+
249+
Sometimes we may need to create multiple instances of a module, for example:
250+
251+
- Creating multiple stores that uses the same module;
252+
- Register the same module multiple times in the same store.
253+
254+
If we use a plain object to declare the state of the module, then that state object will be shared by reference and cause cross store/module state pollution when it's mutated.
255+
256+
This is actually the exact same problem with `data` inside Vue components. So the solution is also the same - use a function for declaring module state (supported in 2.3.0+):
257+
258+
``` js
259+
const MyReusableModule = {
260+
state () {
261+
return {
262+
foo: 'bar'
263+
}
264+
},
265+
// mutations, actions, getters...
266+
}
267+
```

types/index.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ export type Plugin<S> = (store: Store<S>) => any;
8585

8686
export interface Module<S, R> {
8787
namespaced?: boolean;
88-
state?: S;
88+
state?: S | (() => S);
8989
getters?: GetterTree<S, R>;
9090
actions?: ActionTree<S, R>;
9191
mutations?: MutationTree<S>;

0 commit comments

Comments
 (0)