1,安裝vue-meta-info
npm i vue-meta-info --save
2,在main.js文件中引入vue-meta-info
import Vue from 'vue'
import MetaInfo from 'vue-meta-info';
Vue.use(MetaInfo)
3,靜態使用 metaInfo
<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>
3,動態使用 metaInfo
<template>
...
</template>
<script>
export default {
name: 'async',
metaInfo () {
return {
title: this.pageName
}
},
data () {
return {
pageName: 'loading'
}
},
mounted () {
setTimeout(() => {
this.pageName = 'async'
}, 2000)
}
}
</script>
4,如果您使用了Vue SSR 來渲染頁面,那么您需要注意的是:
由於沒有動態更新,所有的生命周期鈎子函數中,只有 beforeCreate 和 created 會在服務器端渲染(SSR)過程中被調用。
這就是說任何其他生命周期鈎子函數中的代碼(例如 beforeMount 或 mounted),只會在客戶端執行。
此外還需要注意的是,你應該避免在 beforeCreate 和 created 生命周期時產生全局副作用的代碼,
例如在其中使用 setInterval 設置 timer。在純客戶端(client-side only)的代碼中,我們可以設置一個 timer,然后在 beforeDestroy 或 destroyed 生命周期時將其銷毀。
但是,由於在 SSR 期間並不會調用銷毀鈎子函數,所以 timer 將永遠保留下來。為了避免這種情況,請將副作用代碼移動到 beforeMount 或 mounted 生命周期中。
5,基於以上約束,我們目前可以使用靜態的數據來渲染我們的metaInfo,下面給出一個使用示例:
<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對象。類似於這樣
context = {
...
title: 'My Example App',
render: {
meta: function () { ... },
link: function () { ... }
}
}
至此,我們可以改造我們的模板:
<!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>