Skip to content

Commit 7255f2c

Browse files
committed
Translate data.md via GitLocalize
1 parent 08e6d79 commit 7255f2c

File tree

1 file changed

+287
-0
lines changed

1 file changed

+287
-0
lines changed

zh/data.md

Lines changed: 287 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,287 @@
1+
# 数据预取和状态
2+
3+
## 数据预取存储容器(Data Store)
4+
5+
在服务器端渲染(SSR)期间,我们本质上是在渲染我们应用程序的"快照",所以如果应用程序依赖于一些异步数据,**那么在开始渲染过程之前,需要先预取和解析好这些数据**
6+
7+
另一个需要关注的问题是在客户端,在挂载(mount)到客户端应用程序之前,需要获取到与服务器端应用程序完全相同的数据 - 否则,客户端应用程序会因为使用与服务器端应用程序不同的状态,然后导致混合失败。
8+
9+
为了解决这个问题,获取的数据需要位于视图组件之外,即放置在专门的数据预取存储容器(data store)或"状态容器(state container))"中。首先,在服务器端,我们可以在渲染之前预取数据,并将数据填充到 store 中。此外,我们将在 HTML 中序列化(serialize)和内联预置(inline)状态。这样,在挂载(mount)到客户端应用程序之前,可以直接从 store 获取到内联预置(inline)状态。
10+
11+
为此,我们将使用官方状态管理库 [Vuex](https://github.com/vuejs/vuex/)。我们先创建一个 `store.js` 文件,里面会模拟一些根据 id 获取 item 的逻辑:
12+
13+
```js
14+
// store.js
15+
import Vue from 'vue'
16+
import Vuex from 'vuex'
17+
Vue.use(Vuex)
18+
// 假定我们有一个可以返回 Promise 的
19+
// 通用 API(请忽略此 API 具体实现细节)
20+
import { fetchItem } from './api'
21+
export function createStore () {
22+
return new Vuex.Store({
23+
state: {
24+
items: {}
25+
},
26+
actions: {
27+
fetchItem ({ commit }, id) {
28+
// `store.dispatch()` 会返回 Promise,
29+
// 以便我们能够知道数据在何时更新
30+
return fetchItem(id).then(item => {
31+
commit('setItem', { id, item })
32+
})
33+
}
34+
},
35+
mutations: {
36+
setItem (state, { id, item }) {
37+
Vue.set(state.items, id, item)
38+
}
39+
}
40+
})
41+
}
42+
```
43+
44+
然后修改 `app.js`
45+
46+
```js
47+
// app.js
48+
import Vue from 'vue'
49+
import App from './App.vue'
50+
import { createRouter } from './router'
51+
import { createStore } from './store'
52+
import { sync } from 'vuex-router-sync'
53+
export function createApp () {
54+
// 创建 router 和 store 实例
55+
const router = createRouter()
56+
const store = createStore()
57+
// 同步路由状态(route state)到 store
58+
sync(store, router)
59+
// 创建应用程序实例,将 router 和 store 注入
60+
const app = new Vue({
61+
router,
62+
store,
63+
render: h => h(App)
64+
})
65+
// 暴露 app, router 和 store。
66+
return { app, router, store }
67+
}
68+
```
69+
70+
## 带有逻辑配置的组件(Logic Collocation with Components)
71+
72+
那么,我们在哪里放置「dispatch 数据预取 action」的代码?
73+
74+
我们需要通过访问路由,来决定获取哪部分数据 - 这也决定了哪些组件需要渲染。事实上,给定路由所需的数据,也是在该路由上渲染组件时所需的数据。所以在路由组件中放置数据预取逻辑,是很自然的事情。
75+
76+
我们将在路由组件上暴露出一个自定义静态函数 `asyncData`。注意,由于此函数会在组件实例化之前调用,所以它无法访问 `this`。需要将 store 和路由信息作为参数传递进去:
77+
78+
```html
79+
<!-- Item.vue -->
80+
<template>
81+
<div>{{ item.title }}</div>
82+
</template>
83+
<script>
84+
export default {
85+
asyncData ({ store, route }) {
86+
// 触发 action 后,会返回 Promise
87+
return store.dispatch('fetchItem', route.params.id)
88+
},
89+
computed: {
90+
// 从 store 的 state 对象中的获取 item。
91+
item () {
92+
return this.$store.state.items[this.$route.params.id]
93+
}
94+
}
95+
}
96+
</script>
97+
```
98+
99+
## 服务器端数据预取(Server Data Fetching)
100+
101+
`entry-server.js` 中,我们可以通过路由获得与 `router.getMatchedComponents()` 相匹配的组件,如果组件暴露出 `asyncData`,我们就调用这个方法。然后我们需要将解析完成的状态,附加到渲染上下文(render context)中。
102+
103+
```js
104+
// entry-server.js
105+
import { createApp } from './app'
106+
export default context => {
107+
return new Promise((resolve, reject) => {
108+
const { app, router, store } = createApp()
109+
router.push(context.url)
110+
router.onReady(() => {
111+
const matchedComponents = router.getMatchedComponents()
112+
if (!matchedComponents.length) {
113+
return reject({ code: 404 })
114+
}
115+
// 对所有匹配的路由组件调用 `asyncData()`
116+
Promise.all(matchedComponents.map(Component => {
117+
if (Component.asyncData) {
118+
return Component.asyncData({
119+
store,
120+
route: router.currentRoute
121+
})
122+
}
123+
})).then(() => {
124+
// 在所有预取钩子(preFetch hook) resolve 后,
125+
// 我们的 store 现在已经填充入渲染应用程序所需的状态。
126+
// 当我们将状态附加到上下文,
127+
// 并且 `template` 选项用于 renderer 时,
128+
// 状态将自动序列化为 `window.__INITIAL_STATE__`,并注入 HTML。
129+
context.state = store.state
130+
resolve(app)
131+
}).catch(reject)
132+
}, reject)
133+
})
134+
}
135+
```
136+
137+
当使用 `template` 时,`context.state` 将作为 `window.__INITIAL_STATE__` 状态,自动嵌入到最终的 HTML 中。而在客户端,在挂载到应用程序之前,store 就应该获取到状态:
138+
139+
```js
140+
// entry-client.js
141+
const { app, router, store } = createApp()
142+
if (window.__INITIAL_STATE__) {
143+
store.replaceState(window.__INITIAL_STATE__)
144+
}
145+
```
146+
147+
## 客户端数据预取(Client Data Fetching)
148+
149+
在客户端,处理数据预取有两种不同方式:
150+
151+
1. **在路由导航之前解析数据:**
152+
153+
使用此策略,应用程序会等待视图所需数据全部解析之后,再传入数据并处理当前视图。好处在于,可以直接在数据准备就绪时,传入视图渲染完整内容,但是如果数据预取需要很长时间,用户在当前视图会感受到"明显卡顿"。因此,如果使用此策略,建议提供一个数据加载指示器(data loading indicator)。
154+
155+
我们可以通过检查匹配的组件,并在全局路由钩子函数中执行 `asyncData` 函数,来在客户端实现此策略。注意,在初始路由准备就绪之后,我们应该注册此钩子,这样我们就不必再次获取服务器提取的数据。
156+
157+
```js
158+
// entry-client.js
159+
// ...忽略无关代码
160+
router.onReady(() => {
161+
// 添加路由钩子函数,用于处理 asyncData.
162+
// 在初始路由 resolve 后执行,
163+
// 以便我们不会二次预取(double-fetch)已有的数据。
164+
// 使用 `router.beforeResolve()`,以便确保所有异步组件都 resolve。
165+
router.beforeResolve((to, from, next) => {
166+
const matched = router.getMatchedComponents(to)
167+
const prevMatched = router.getMatchedComponents(from)
168+
// 我们只关心之前没有渲染的组件
169+
// 所以我们对比它们,找出两个匹配列表的差异组件
170+
let diffed = false
171+
const activated = matched.filter((c, i) => {
172+
return diffed || (diffed = (prevMatched[i] !== c))
173+
})
174+
if (!activated.length) {
175+
return next()
176+
}
177+
// 这里如果有加载指示器(loading indicator),就触发
178+
Promise.all(activated.map(c => {
179+
if (c.asyncData) {
180+
return c.asyncData({ store, route: to })
181+
}
182+
})).then(() => {
183+
// 停止加载指示器(loading indicator)
184+
next()
185+
}).catch(next)
186+
})
187+
app.$mount('#app')
188+
})
189+
```
190+
191+
1. **匹配要渲染的视图后,再获取数据:**
192+
193+
此策略将客户端数据预取逻辑,放在视图组件的 `beforeMount` 函数中。当路由导航被触发时,可以立即切换视图,因此应用程序具有更快的响应速度。然而,传入视图在渲染时不会有完整的可用数据。因此,对于使用此策略的每个视图组件,都需要具有条件加载状态。
194+
195+
这可以通过纯客户端(client-only)的全局 mixin 来实现:
196+
197+
```js
198+
Vue.mixin({
199+
beforeMount () {
200+
const { asyncData } = this.$options
201+
if (asyncData) {
202+
// 将获取数据操作分配给 promise
203+
// 以便在组件中,我们可以在数据准备就绪后
204+
// 通过运行 `this.dataPromise.then(...)` 来执行其他任务
205+
this.dataPromise = asyncData({
206+
store: this.$store,
207+
route: this.$route
208+
})
209+
}
210+
}
211+
})
212+
```
213+
214+
这两种策略是根本上不同的用户体验决策,应该根据你创建的应用程序的实际使用场景进行挑选。但是无论你选择哪种策略,当路由组件重用(同一路由,但是 params 或 query 已更改,例如,从 `user/1``user/2`)时,也应该调用 `asyncData` 函数。我们也可以通过纯客户端(client-only)的全局 mixin 来处理这个问题:
215+
216+
```js
217+
Vue.mixin({
218+
beforeRouteUpdate (to, from, next) {
219+
const { asyncData } = this.$options
220+
if (asyncData) {
221+
asyncData({
222+
store: this.$store,
223+
route: to
224+
}).then(next).catch(next)
225+
} else {
226+
next()
227+
}
228+
}
229+
})
230+
```
231+
232+
## Store 代码拆分(Store Code Splitting)
233+
234+
在大型应用程序中,我们的 Vuex store 可能会分为多个模块。当然,也可以将这些模块代码,分割到相应的路由组件 chunk 中。假设我们有以下 store 模块:
235+
236+
```js
237+
// store/modules/foo.js
238+
export default {
239+
namespaced: true,
240+
// 重要信息:state 必须是一个函数,
241+
// 因此可以创建多个实例化该模块
242+
state: () => ({
243+
count: 0
244+
}),
245+
actions: {
246+
inc: ({ commit }) => commit('inc')
247+
},
248+
mutations: {
249+
inc: state => state.count++
250+
}
251+
}
252+
```
253+
254+
我们可以在路由组件的 `asyncData` 钩子函数中,使用 `store.registerModule` 惰性注册(lazy-register)这个模块:
255+
256+
```html
257+
// 在路由组件内
258+
<template>
259+
<div>{{ fooCount }}</div>
260+
</template>
261+
<script>
262+
// 在这里导入模块,而不是在 `store/index.js` 中
263+
import fooStoreModule from '../store/modules/foo'
264+
export default {
265+
asyncData ({ store }) {
266+
store.registerModule('foo', fooStoreModule)
267+
return store.dispatch('foo/inc')
268+
},
269+
// 重要信息:当多次访问路由时,
270+
// 避免在客户端重复注册模块。
271+
destroyed () {
272+
this.$store.unregisterModule('foo')
273+
},
274+
computed: {
275+
fooCount () {
276+
return this.$store.state.foo.count
277+
}
278+
}
279+
}
280+
</script>
281+
```
282+
283+
由于模块现在是路由组件的依赖,所以它将被 webpack 移动到路由组件的异步 chunk 中。
284+
285+
---
286+
287+
哦?看起来要写很多代码!这是因为,通用数据预取可能是服务器渲染应用程序中最复杂的问题,我们正在为下一步开发做前期准备。一旦设定好模板示例,创建单独组件实际上会变得相当轻松。

0 commit comments

Comments
 (0)