Step1. 安裝:
$ npm install vue-meta --save
|
router.js
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
<template> <div id="app"> <router-view></router-view> </div> </template>
<script> export default { name: 'App', metaInfo: { |
Home.vue
<template> <div id="page"> <h1>這是首頁</h1> </div> </template>
<script> export default { name: 'Home', metaInfo: { title: '這是一個首頁', |
About.vue
<template> <div id="page"> <h1>關於我們</h1> </div> </template>
<script> export default { name: 'About', metaInfo: { |
如果想定義其他meta信息,可以使用vue-meta的API。
例如 meta
:
{ metaInfo: { meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' } ] } }
|
output :
<meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1">
|
異步請求數據定義
如果component中使用了異步請求數據,可以使用 metaInfo()
方法。
Post.vue:
<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) => { |
這樣就很輕松地完成了頁面meta info的設定。
源作者:http://www.zhuyuwei.cn/2018/vue-meta-for-vuejs.html