Skip to content

Commit 35548a6

Browse files
committedMay 18, 2017
Merge remote-tracking branch 'upstream/master' into working
# Conflicts: # en/universal.md
2 parents b2e816d + 3563338 commit 35548a6

File tree

6 files changed

+122
-5
lines changed

6 files changed

+122
-5
lines changed
 

‎en/api.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,8 @@ See [Introducing the Server Bundle](./bundle-renderer.md) and [Build Configurati
8282
- #### `clientManifest`
8383

8484
- 2.3.0+
85-
- only used in `createBundleRenderer`
8685

87-
Provide a client build manifest object generated by `vue-server-renderer/server-plugin`. The client manifest provides the bundle renderer with the proper information for automatic asset injection into the HTML template. For more details, see [Generating clientManifest](./build-config.md#generating-clientmanifest).
86+
Provide a client build manifest object generated by `vue-server-renderer/client-plugin`. The client manifest provides the bundle renderer with the proper information for automatic asset injection into the HTML template. For more details, see [Generating clientManifest](./build-config.md#generating-clientmanifest).
8887

8988
- #### `inject`
9089

‎en/bundle-renderer.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ const renderer = createBundleRenderer(serverBundle, {
3838
// inside a server handler...
3939
server.get('*', (req, res) => {
4040
const context = { url: req.url }
41-
// No need to pass an app here because it is auto-created by the
41+
// No need to pass an app here because it is auto-created by
4242
// executing the bundle. Now our server is decoupled from our Vue app!
4343
renderer.renderToString(context, (err, html) => {
4444
// handle error...

‎en/data.md

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ export default {
9797
9898
computed: {
9999
// display the item from store state.
100-
items () {
100+
item () {
101101
return this.$store.state.items[this.$route.params.id]
102102
}
103103
}
@@ -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.

‎en/universal.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ Etant donné que le processus de rendu actuel doit être déterministe, nous all
1212

1313
Vu qu'il n'y a pas de mises à jour dynamiques, de tous les hooks de cycles de vie, seuls `beforeCreate` et `created` seront appelés pendant le rendu côté serveur. Cela signifie que tout code présent dans d'autres hooks tels que `beforeMount` ou `mounted` sera exécuté uniquement côté client.
1414

15+
Une autre chose a noter est que vous devriez éviter la création d'effets de bord globaux dans `beforeCreate` et `created` comme ceux, par exemple, dus aux timers avec `setInterval`. Nous pouvons mettre en place des timers seulement dans du code côté client qui seront arrêtés pendant les phases `beforeDestroy` et `destroyed`. Cependant, comme ces hooks ne sont jamais appelés pendant le SSR, les timers vont continuer de tourner éternellement. Pour éviter cela, déplacez ce type d'effet de bord dans les hooks `beforeMount` ou `mounted`.
16+
1517
## Accès aux APIs spécifiques à la plateforme
1618

1719
Le code universel ne peut pas accéder aux APIs spécifiques à une plateforme. Ainsi, si votre code utilise directement les variables globales exclusives au navigateur comme `window` ou `document`, elles lèveront des erreurs si elles sont exécutées sur Node.js, et vice-versa.

‎ru/data.md

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ export default {
9797
9898
computed: {
9999
// отображаем элемент из состояния хранилища.
100-
items () {
100+
item () {
101101
return this.$store.state.items[this.$route.params.id]
102102
}
103103
}
@@ -254,6 +254,63 @@ Vue.mixin({
254254
})
255255
```
256256

257+
## Разделение кода хранилища
258+
259+
В большом приложении хранилище Vuex будет скорее всего разделено на несколько модулей. Конечно, также можно разделить код этих модулей на соответствующие фрагменты компонента маршрута. Предположим, что у нас есть следующий модуль хранилища:
260+
261+
``` js
262+
// store/modules/foo.js
263+
export default {
264+
namespaced: true,
265+
// ВАЖНО: state должен быть функцией, чтобы
266+
// модуль мог инстанцироваться несколько раз
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+
Мы можем использовать `store.registerModule` для lazy-регистрации этого модуля в хуке `asyncData` компонента маршрута:
280+
281+
``` html
282+
// внутри компонента маршрута
283+
<template>
284+
<div>{{ fooCount }}</div>
285+
</template>
286+
287+
<script>
288+
// импортируем модуль здесь, а не в `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+
// ВАЖНО: избегайте дублирования регистрации модуля на клиенте
298+
// когда маршрут посещается несколько раз.
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+
Поскольку модуль теперь является зависимостью компонента маршрута, он будет перемещён в асинхронный фрагмент компонента маршрута с помощью Webpack.
313+
257314
---
258315

259316
Фух, это было много кода! Это связано с тем, что универсальная загрузка данных является, вероятно, самой сложной проблемой в приложении с рендерингом на стороне сервера, и таким образом мы закладываем хороший фундамент для облегчения дальнейшей разработки. После создания такой заготовки, создание отдельных компонентов будет приятным занятием.

‎ru/universal.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212

1313
Так как динамических обновлений нет, из всех хуков жизненного цикла будут вызваны только `beforeCreate` и `created` во время серверного рендеринга (SSR). Это означает, что код внутри любых других хуков жизненного цикла, таких как `beforeMount` или `mounted`, будет выполняться только на клиенте.
1414

15+
Стоит ещё отметить, что вам следует избегать кода, который производит глобальные побочные эффекты (side effects) в хуках `beforeCreate` и `created`, например устанавливая таймеры с помощью `setInterval`. В коде на стороне клиента мы можем установить таймер, а затем остановить его в `beforeDestroy` или `destroyed`. Но, поскольку хуки уничтожения не будут вызываться во время SSR, таймеры останутся навсегда. Чтобы избежать этого, переместите такой код в `beforeMount` или `mounted`.
16+
1517
## Доступ к специализированному API платформы
1618

1719
Универсальный код не может использовать API специализированное для какой-то конкретной платформы (platform-specific APIs), потому что если ваш код будет использовать глобальные переменные браузеров `window` или `document`, то возникнут ошибки при выполнении в Node.js, и наоборот.

0 commit comments

Comments
 (0)
Please sign in to comment.