Skip to content

Commit e392831

Browse files
committed
document how to code-split store modules
1 parent ad6c62e commit e392831

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

en/data.md

+57
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,63 @@ Vue.mixin({
254254
})
255255
```
256256

257+
## Store Code Splitting
258+
259+
In a large application, our vuex store will likely be split into multiple modules. Of course, it is also possible to code-split these modules into corresponding route component chunks. Suppose we have the following store module:
260+
261+
``` js
262+
// store/modules/foo.js
263+
export default {
264+
namespaced: true,
265+
// IMPORTANT: state must be a function so the module can be
266+
// instantiated multiple times
267+
state: () => ({
268+
count: 0
269+
}),
270+
actions: {
271+
inc: ({ commit }) => commit('inc')
272+
},
273+
mutations: {
274+
inc: state => state.count++
275+
}
276+
}
277+
```
278+
279+
We can use `store.registerModule` to lazy-register this module in a route component's `asyncData` hook:
280+
281+
``` html
282+
// inside a route component
283+
<template>
284+
<div>{{ fooCount }}</div>
285+
</template>
286+
287+
<script>
288+
// import the module here instead of in `store/index.js`
289+
import fooStoreModule from '../store/modules/foo'
290+
291+
export default {
292+
asyncData ({ store }) {
293+
store.registerModule('foo', fooStoreModule)
294+
return store.dispatch('foo/inc')
295+
},
296+
297+
// IMPORTANT: avoid duplicate module registration on the client
298+
// when the route is visited multiple times.
299+
destroyed () {
300+
this.$store.unregisterModule('foo')
301+
},
302+
303+
computed: {
304+
fooCount () {
305+
return this.$store.state.foo.count
306+
}
307+
}
308+
}
309+
</script>
310+
```
311+
312+
Because the module is now a dependency of the route component, it will be moved into the route component's async chunk by webpack.
313+
257314
---
258315

259316
Phew, that was a lot of code! This is because universal data-fetching is probably the most complex problem in a server-rendered app and we are laying the groundwork for easier further development. Once the boilerplate is set up, authoring individual components will be actually quite pleasant.

0 commit comments

Comments
 (0)