You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/guide/data.md
+98-135
Original file line number
Diff line number
Diff line change
@@ -2,11 +2,9 @@
2
2
3
3
## Data Store
4
4
5
-
During SSR, we are essentially rendering a "snapshot" of our app, so if the app relies on some asynchronous data, **these data need to be pre-fetched and resolved before we start the rendering process**.
5
+
During SSR, we are essentially rendering a "snapshot" of our app. The asynchronous data from our components needs to be available before we mount the client side app - otherwise the client app would render using different state and the hydration would fail.
6
6
7
-
Another concern is that on the client, the same data needs to be available before we mount the client side app - otherwise the client app would render using different state and the hydration would fail.
8
-
9
-
To address this, the fetched data needs to live outside the view components, in a dedicated data store, or a "state container". On the server, we can pre-fetch and fill data into the store before rendering. In addition, we will serialize and inline the state in the HTML. The client-side store can directly pick up the inlined state before we mount the app.
7
+
To address this, the fetched data needs to live outside the view components, in a dedicated data store, or a "state container". On the server, we can pre-fetch and fill data into the store while rendering. In addition, we will serialize and inline the state in the HTML after the app has finished rendering. The client-side store can directly pick up the inlined state before we mount the app.
10
8
11
9
We will be using the official state management library [Vuex](https://github.com/vuejs/vuex/) for this purpose. Let's create a `store.js` file, with some mocked logic for fetching an item based on an id:
12
10
@@ -23,9 +21,12 @@ import { fetchItem } from './api'
23
21
24
22
exportfunctioncreateStore () {
25
23
returnnewVuex.Store({
26
-
state: {
24
+
// IMPORTANT: state must be a function so the module can be
25
+
// instantiated multiple times
26
+
state: () => ({
27
27
items: {}
28
-
},
28
+
}),
29
+
29
30
actions: {
30
31
fetchItem ({ commit }, id) {
31
32
// return the Promise via `store.dispatch()` so that we know
@@ -35,6 +36,7 @@ export function createStore () {
35
36
})
36
37
}
37
38
},
39
+
38
40
mutations: {
39
41
setItem (state, { id, item }) {
40
42
Vue.set(state.items, id, item)
@@ -44,6 +46,11 @@ export function createStore () {
44
46
}
45
47
```
46
48
49
+
::: warning
50
+
Most of the time, you should wrap `state` in a function, so that it will not leak into the next server-side runs.
@@ -80,34 +87,64 @@ So, where do we place the code that dispatches the data-fetching actions?
80
87
81
88
The data we need to fetch is determined by the route visited - which also determines what components are rendered. In fact, the data needed for a given route is also the data needed by the components rendered at that route. So it would be natural to place the data fetching logic inside route components.
82
89
83
-
We will expose a custom static function `asyncData` on our route components. Note because this function will be called before the components are instantiated, it doesn't have access to `this`. The store and route information needs to be passed in as arguments:
90
+
We will use the `ssrPrefetch` option in our components. This option is recognized by the server renderer and will be pause the component render until the promise it returns is resolved. Since the component instance is already created at this point, it has access to `this`.
91
+
92
+
::: tip
93
+
You can use `ssrPrefetch` in any component, not just the route-level components.
94
+
:::
95
+
96
+
Here is an example `Item.vue` component that is rendered at the `'/item/:id'` route:
You should check if the component was server-side rendered in the `mounted` hook to avoid executing the logic twice.
143
+
:::
144
+
108
145
## Server Data Fetching
109
146
110
-
In `entry-server.js` we can get the components matched by a route with `router.getMatchedComponents()`, and call `asyncData` if the component exposes it. Then we need to attach resolved state to the render context.
147
+
In `entry-server.js`, we will set the store state in the render context after the app is finished rendering, thanks to the `context.rendered` hook recognized by the server renderer.
// call `asyncData()` on all matched route components
129
-
Promise.all(matchedComponents.map(Component=> {
130
-
if (Component.asyncData) {
131
-
returnComponent.asyncData({
132
-
store,
133
-
route:router.currentRoute
134
-
})
135
-
}
136
-
})).then(() => {
137
-
// After all preFetch hooks are resolved, our store is now
138
-
// filled with the state needed to render the app.
160
+
// This `rendered` hook is called when the app has finished rendering
161
+
context.rendered= () => {
162
+
// After the app is rendered, our store is now
163
+
// filled with the state from our components.
139
164
// When we attach the state to the context, and the `template` option
140
165
// is used for the renderer, the state will automatically be
141
166
// serialized and injected into the HTML as `window.__INITIAL_STATE__`.
142
167
context.state=store.state
168
+
}
143
169
144
-
resolve(app)
145
-
}).catch(reject)
170
+
resolve(app)
146
171
}, reject)
147
172
})
148
173
}
@@ -153,105 +178,14 @@ When using `template`, `context.state` will automatically be embedded in the fin
153
178
```js
154
179
// entry-client.js
155
180
156
-
const { app, router, store } =createApp()
181
+
const { app, store } =createApp()
157
182
158
183
if (window.__INITIAL_STATE__) {
184
+
// We initialize the store state with the data injected from the server
159
185
store.replaceState(window.__INITIAL_STATE__)
160
186
}
161
-
```
162
-
163
-
## Client Data Fetching
164
-
165
-
On the client, there are two different approaches for handling data fetching:
166
-
167
-
1.**Resolve data before route navigation:**
168
-
169
-
With this strategy, the app will stay on the current view until the data needed by the incoming view has been resolved. The benefit is that the incoming view can directly render the full content when it's ready, but if the data fetching takes a long time, the user will feel "stuck" on the current view. It is therefore recommended to provide a data loading indicator if using this strategy.
170
-
171
-
We can implement this strategy on the client by checking matched components and invoking their `asyncData` function inside a global route hook. Note we should register this hook after the initial route is ready so that we don't unnecessarily fetch the server-fetched data again.
172
-
173
-
```js
174
-
// entry-client.js
175
-
176
-
// ...omitting unrelated code
177
-
178
-
router.onReady(() => {
179
-
// Add router hook for handling asyncData.
180
-
// Doing it after initial route is resolved so that we don't double-fetch
181
-
// the data that we already have. Using `router.beforeResolve()` so that all
// this is where we should trigger a loading indicator if there is one
199
187
200
-
Promise.all(activated.map(c=> {
201
-
if (c.asyncData) {
202
-
returnc.asyncData({ store, route: to })
203
-
}
204
-
})).then(() => {
205
-
206
-
// stop loading indicator
207
-
208
-
next()
209
-
}).catch(next)
210
-
})
211
-
212
-
app.$mount('#app')
213
-
})
214
-
```
215
-
216
-
2.**Fetch data after the matched view is rendered:**
217
-
218
-
This strategy places the client-side data-fetching logic in a view component's `beforeMount` function. This allows the views to switch instantly when a route navigation is triggered, so the app feels a bit more responsive. However, the incoming view will not have the full data available when it's rendered. It is therefore necessary to have a conditional loading state for each view component that uses this strategy.
219
-
220
-
This can be achieved with a client-only global mixin:
221
-
222
-
```js
223
-
Vue.mixin({
224
-
beforeMount () {
225
-
const { asyncData } =this.$options
226
-
if (asyncData) {
227
-
// assign the fetch operation to a promise
228
-
// so that in components we can do `this.dataPromise.then(...)` to
229
-
// perform other tasks after data is ready
230
-
this.dataPromise=asyncData({
231
-
store:this.$store,
232
-
route:this.$route
233
-
})
234
-
}
235
-
}
236
-
})
237
-
```
238
-
239
-
The two strategies are ultimately different UX decisions and should be picked based on the actual scenario of the app you are building. But regardless of which strategy you pick, the `asyncData` function should also be called when a route component is reused (same route, but params or query changed. e.g. from `user/1` to `user/2`). We can also handle this with a client-only global mixin:
240
-
241
-
```js
242
-
Vue.mixin({
243
-
beforeRouteUpdate (to, from, next) {
244
-
const { asyncData } =this.$options
245
-
if (asyncData) {
246
-
asyncData({
247
-
store:this.$store,
248
-
route: to
249
-
}).then(next).catch(next)
250
-
} else {
251
-
next()
252
-
}
253
-
}
254
-
})
188
+
app.$mount('#app')
255
189
```
256
190
257
191
## Store Code Splitting
@@ -262,14 +196,17 @@ In a large application, our Vuex store will likely be split into multiple module
262
196
// store/modules/foo.js
263
197
exportdefault {
264
198
namespaced:true,
199
+
265
200
// IMPORTANT: state must be a function so the module can be
266
201
// instantiated multiple times
267
202
state: () => ({
268
203
count:0
269
204
}),
205
+
270
206
actions: {
271
207
inc: ({ commit }) =>commit('inc')
272
208
},
209
+
273
210
mutations: {
274
211
inc:state=>state.count++
275
212
}
@@ -289,9 +226,30 @@ We can use `store.registerModule` to lazy-register this module in a route compon
289
226
importfooStoreModulefrom'../store/modules/foo'
290
227
291
228
exportdefault {
292
-
asyncData ({ store }) {
293
-
store.registerModule('foo', fooStoreModule)
294
-
returnstore.dispatch('foo/inc')
229
+
computed: {
230
+
fooCount () {
231
+
returnthis.$store.state.foo.count
232
+
}
233
+
},
234
+
235
+
// Server-side only
236
+
ssrPrefetch () {
237
+
this.registerFoo()
238
+
returnthis.fooInc()
239
+
},
240
+
241
+
// Client-side only
242
+
mounted () {
243
+
// We already incremented 'count' on the server
244
+
// We know by checking if the 'foo' state already exists
245
+
constalreadyIncremented=!!this.$store.state.foo
246
+
247
+
// We register the foo module
248
+
this.registerFoo()
249
+
250
+
if (!alreadyIncremented) {
251
+
this.fooInc()
252
+
}
295
253
},
296
254
297
255
// IMPORTANT: avoid duplicate module registration on the client
@@ -300,9 +258,14 @@ export default {
300
258
this.$store.unregisterModule('foo')
301
259
},
302
260
303
-
computed: {
304
-
fooCount () {
305
-
returnthis.$store.state.foo.count
261
+
methods: {
262
+
registerFoo () {
263
+
// Preserve the previous state if it was injected from the server
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
276
314
-
---
315
-
316
-
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.
277
+
::: warning
278
+
Don't forget to use the `preserveState: true` option for `registerModule` so we keep the state injected by the server.
0 commit comments