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
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
@@ -80,34 +78,79 @@ So, where do we place the code that dispatches the data-fetching actions?
80
78
81
79
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
80
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:
81
+
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`.
// (for example, log it into a monitoring service)
144
+
})
145
+
}
103
146
}
104
147
}
105
148
</script>
106
149
```
107
150
108
151
## Server Data Fetching
109
152
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.
153
+
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.
166
+
// This `rendered` hook is called when the app has finished rendering
167
+
context.rendered= () => {
168
+
// After the app is rendered, our store is now
169
+
// filled with the state from our components.
139
170
// When we attach the state to the context, and the `template` option
140
171
// is used for the renderer, the state will automatically be
141
172
// serialized and injected into the HTML as `window.__INITIAL_STATE__`.
142
173
context.state=store.state
174
+
}
143
175
144
-
resolve(app)
145
-
}).catch(reject)
176
+
resolve(app)
146
177
}, reject)
147
178
})
148
179
}
@@ -153,105 +184,14 @@ When using `template`, `context.state` will automatically be embedded in the fin
153
184
```js
154
185
// entry-client.js
155
186
156
-
const { app, router, store } =createApp()
187
+
const { app, store } =createApp()
157
188
158
189
if (window.__INITIAL_STATE__) {
190
+
// We initialize the store state with the data injected from the server
159
191
store.replaceState(window.__INITIAL_STATE__)
160
192
}
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
193
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
-
})
194
+
app.$mount('#app')
255
195
```
256
196
257
197
## Store Code Splitting
@@ -289,9 +229,18 @@ We can use `store.registerModule` to lazy-register this module in a route compon
289
229
importfooStoreModulefrom'../store/modules/foo'
290
230
291
231
exportdefault {
292
-
asyncData ({ store }) {
293
-
store.registerModule('foo', fooStoreModule)
294
-
returnstore.dispatch('foo/inc')
232
+
computed: {
233
+
fooCount () {
234
+
returnthis.$store.state.foo.count
235
+
}
236
+
},
237
+
238
+
ssrPrefetch () {
239
+
returnthis.fooInc()
240
+
},
241
+
242
+
mounted () {
243
+
this.fooInc()
295
244
},
296
245
297
246
// IMPORTANT: avoid duplicate module registration on the client
@@ -300,17 +249,14 @@ export default {
300
249
this.$store.unregisterModule('foo')
301
250
},
302
251
303
-
computed: {
304
-
fooCount () {
305
-
returnthis.$store.state.foo.count
252
+
methods: {
253
+
fooInc () {
254
+
this.$store.registerModule('foo', fooStoreModule)
255
+
returnthis.$store.dispatch('foo/inc')
306
256
}
307
257
}
308
258
}
309
259
</script>
310
260
```
311
261
312
262
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
-
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.
0 commit comments