Skip to content

Commit b166a95

Browse files
Merge pull request #69 from dear-lizhihua/gitlocalize-114
zh/head.md
2 parents 51d2ec8 + b3031bd commit b166a95

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

zh/head.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Head 管理
2+
3+
类似于资源注入,Head 管理遵循相同的理念:我们可以在组件的生命周期中,将数据动态地追加到渲染`上下文`(render context),然后在`模板`中的占位符替换为这些数据。
4+
5+
> 在 >=2.3.2 的版本,您可以通过 `this.$ssrContext` 来直接访问组件中的服务器端渲染上下文(SSR context)。在旧版本中,您必须通过将其传递给 `createApp()` 并将其暴露于根实例的 `$options` 上,才能手动注入服务器端渲染上下文(SSR context) - 然后子组件可以通过 `this.$root.$options.ssrContext` 来访问它。
6+
7+
我们可以编写一个简单的 mixin 来完成标题管理:
8+
9+
```js
10+
// title-mixin.js
11+
function getTitle (vm) {
12+
// 组件可以提供一个 `title` 选项
13+
// 此选项可以是一个字符串或函数
14+
const { title } = vm.$options
15+
if (title) {
16+
return typeof title === 'function'
17+
? title.call(vm)
18+
: title
19+
}
20+
}
21+
const serverTitleMixin = {
22+
created () {
23+
const title = getTitle(this)
24+
if (title) {
25+
this.$ssrContext.title = title
26+
}
27+
}
28+
}
29+
const clientTitleMixin = {
30+
mounted () {
31+
const title = getTitle(this)
32+
if (title) {
33+
document.title = title
34+
}
35+
}
36+
}
37+
// 可以通过 webpack.DefinePlugin 注入 VUE_ENV
38+
export default process.env.VUE_ENV === 'server'
39+
? serverTitleMixin
40+
: clientTitleMixin
41+
```
42+
43+
现在,路由组件可以利用以上 mixin,来控制文档标题(document title):
44+
45+
```js
46+
// Item.vue
47+
export default {
48+
mixins: [titleMixin],
49+
title () {
50+
return this.item.title
51+
}
52+
asyncData ({ store, route }) {
53+
return store.dispatch('fetchItem', route.params.id)
54+
},
55+
computed: {
56+
item () {
57+
return this.$store.state.items[this.$route.params.id]
58+
}
59+
}
60+
}
61+
```
62+
63+
然后 `template` 的内容将会传递给 bundle renderer:
64+
65+
```html
66+
<html>
67+
<head>
68+
<title>{{ title }}</title>
69+
</head>
70+
<body>
71+
...
72+
</body>
73+
</html>
74+
```
75+
76+
**注意:**
77+
78+
- 使用双花括号(double-mustache)进行 HTML 转义插值(HTML-escaped interpolation),以避免 XSS 攻击。
79+
- 你应该在创建 `context` 对象时提供一个默认标题,以防在渲染过程中组件没有设置标题。
80+
81+
---
82+
83+
使用相同的策略,您可以轻松地将此 mixin 扩展为通用的头部管理工具(generic head management utility)。

0 commit comments

Comments
 (0)