# vue-meta-info
基于Vue 2.0 的單頁面 meta info 管理。
## 安裝
### Yarn
~~~
$?yarn?add?vue-meta-info
~~~
### NPM
~~~shell
$?npm?install?vue-meta-info?--save
~~~
## 示例
```html
<template>
...
</template>
<script>
export default {
metaInfo: {
title: 'My Example App', // set a title
meta: [{ // set meta
name: 'keyWords',
content: 'My Example App'
}]
link: [{ // set link
rel: 'asstes',
href: 'https://assets-cdn.github.com/'
}]
}
}
</script>
```
1. 全局引入`vue-meta-info`
~~~js
import?Vue?from?'vue'
import?MetaInfo?from?'vue-meta-info'
Vue.use(MetaInfo)
~~~
2. 組件內靜態使用 metaInfo
如:示例
3. 如果你的title或者meta是異步加載的,那么你可能需要這樣使用
```html
<template>
...
</template>
<script>
export default {
name: 'async',
metaInfo () {
return {
title: this.pageName
}
},
data () {
return {
pageName: 'loading'
}
},
mounted () {
setTimeout(() => {
this.pageName = 'async'
}, 2000)
}
}
</script>
```
4. SSR
如果您使用了Vue SSR 來渲染頁面,那么您需要注意的是:
由于沒有動態更新,所有的生命周期鉤子函數中,只有 beforeCreate 和 created 會在服務器端渲染(SSR)過程中被調用。這就是說任何其他生命周期鉤子函數中的代碼(例如 beforeMount 或 mounted),只會在客戶端執行。 此外還需要注意的是,你應該避免在 beforeCreate 和 created 生命周期時產生全局副作用的代碼,例如在其中使用 setInterval 設置 timer。在純客戶端(client-side only)的代碼中,我們可以設置一個 timer,然后在 beforeDestroy 或 destroyed 生命周期時將其銷毀。但是,由于在 SSR 期間并不會調用銷毀鉤子函數,所以 timer 將永遠保留下來。為了避免這種情況,請將副作用代碼移動到 beforeMount 或 mounted 生命周期中。
*基于以上約束,我們目前可以使用靜態的數據來渲染我們的`metaInfo`,下面給出一個使用示例:*
```html
<template>
...
</template>
<script>
export default {
metaInfo: {
title: 'My Example App', // set a title
meta: [{ // set meta
name: 'keyWords',
content: 'My Example App'
}]
link: [{ // set link
rel: 'asstes',
href: 'https://assets-cdn.github.com/'
}]
}
}
</script>
```
*此時`vueMetaInfo`會幫我們在ssr的context中掛載出一個title變量和一個render對象。類似于這樣:*
```js
context = {
...
title: 'My Example App',
render: {
meta: function () { ... },
link: function () { ... }
}
}
```
*至此,我們可以改造我們的模板:*
~~~html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>{{title}}</title>
{{{render.meta && render.meta()}}}
{{{render.link && render.link()}}}
</head>
<body>
<!--vue-ssr-outlet-->
</body>
</html>
~~~
*這樣便可以渲染出需要的數據。值得注意的是:雖然我們可以使用*
```html
<template>
...
</template>
<script>
export default {
name: 'async',
metaInfo () {
return {
title: this.pageName
}
},
data () {
return {
pageName: 'loading'
}
},
mounted () {
setTimeout(() => {
this.pageName = 'async'
}, 2000)
}
}
</script>
```
這種形式來定義數據,但是最終渲染出來的`title`依然是`loading`,因為服務端渲染除了`created`和`beforeCreate`并沒有`mounted`鉤子。