vue-meta的官方文檔在這里。
文檔中比較詳細地說明了在瀏覽器端和服務器端如何使用 vue-meta 修改頁面頭部信息,這里我主要介紹下在SPA項目中管理meta info的使用方法。,
vue單頁運用中,對單獨頁面使用meta的時候,他不是直接修改,而是插在下面覆蓋上面的meta進行修改。
1、安裝
npm install vue-meta --save
2、在main.js引入
import Meta from 'vue-meta' Vue.use(Meta)
3、為需要修改的頁面單獨定義metaInfo
export default { metaInfo: { title: 'This is the test', meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=2,user-scalable=yes' } ] } }
4、異步請求數據可以使用
如果component中使用了異步請求數據,可以使用 metaInfo() 方法。
<template>
<div>
<h1>{{{ title }}}</h1>
</div>
</template>
<script>
export default {
name: 'post',
data () {
return {
title: ''
description: '這是一篇文章...'
}
},
metaInfo () {
return {
title: this.title,
meta: [
{ vmid: 'description', name: 'description', content: this.description }
]
}
},
created () {
this.initData()
},
methods: {
initData () {
axios.get('some/url').then((resp) => {
// 設置title時 metaInfo 會同時更新
this.title = resp.title
this.description = resp.decription
})
}
}
}
</script>
