Skip to content

Commit

Permalink
document module reuse
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Apr 13, 2017
1 parent f8b9eda commit a86bd2d
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
22 changes: 22 additions & 0 deletions docs/en/modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -243,3 +243,25 @@ The module's state will be exposed as `store.state.myModule` and `store.state.ne
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.

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.

### Module Reuse

Sometimes we may need to create multiple instances of a module, for example:

- Creating multiple stores that uses the same module;
- Register the same module multiple times in the same store.

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.

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+):

``` js
const MyReusableModule = {
state () {
return {
foo: 'bar'
}
},
// mutations, actions, getters...
}
```
2 changes: 1 addition & 1 deletion types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ export type Plugin<S> = (store: Store<S>) => any;

export interface Module<S, R> {
namespaced?: boolean;
state?: S;
state?: S | (() => S);
getters?: GetterTree<S, R>;
actions?: ActionTree<S, R>;
mutations?: MutationTree<S>;
Expand Down

0 comments on commit a86bd2d

Please sign in to comment.