用于管理 Vue 2.0 中页面 meta 信息,支持SSR(服务器端渲染)
vue-meta的官方文档在这里。
文档中比较详细地说明了在浏览器端和服务器端如何使用 vue-meta 修改页面头部信息,这里我主要介绍下在SPA项目中管理meta info的使用方法。
Step1. 安装:
1
| $ npm install vue-meta --save
|
router.js
1 2 3 4 5 6 7 8 9 10
| import Vue from 'vue' import Router from 'vue-router' import Meta from 'vue-meta'
Vue.use(Router) Vue.use(Meta)
export default new Router({ })
|
在任何一个component中都可以定义 metaInfo 属性
App.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <template> <div id="app"> <router-view></router-view> </div> </template>
<script> export default { name: 'App', metaInfo: { title: '首页', titleTemplate: '%s | 我的Vuejs网站' } } </script>
|
Home.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <template> <div id="page"> <h1>这是首页</h1> </div> </template>
<script> export default { name: 'Home', metaInfo: { title: '这是一个首页', titleTemplate: null } } </script>
|
About.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <template> <div id="page"> <h1>关于我们</h1> </div> </template>
<script> export default { name: 'About', metaInfo: { title: '关于我们' } } </script>
|
如果想定义其他meta信息,可以使用vue-meta的API。
例如 meta
:
1 2 3 4 5 6 7 8
| { metaInfo: { meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' } ] } }
|
output :
1 2
| <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1">
|
异步请求数据定义
如果component中使用了异步请求数据,可以使用 metaInfo()
方法。
Post.vue:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| <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) => { this.title = resp.title this.description = resp.decription }) } } } </script>
|
这样就很轻松地完成了页面meta info的设定。