vue动态改title

Step1. 安装:

$ npm install vue-meta --save

Step2. 在 router.js 中引入 vue-meta

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({
//...
})

 

Step3. 开始定义 metaInfo

在任何一个component中都可以定义 metaInfo 属性

App.vue

<template>
<div id="app">
<router-view></router-view>
</div>
</template>

<script>
export default {
name: 'App',
metaInfo: {
// 如果子component中没有定义 metaInfo.title ,会默认使用这个title
title: '首页',
titleTemplate: '%s | 我的Vuejs网站'
}
}
</script>

 

Home.vue

<template>
<div id="page">
<h1>这是首页</h1>
</div>
</template>

<script>
export default {
name: 'Home',
metaInfo: {
title: '这是一个首页',
// 这里定义titleTemplate会覆盖App.vue中的定义
titleTemplate: null
}
}
</script>

 

About.vue

<template>
<div id="page">
<h1>关于我们</h1>
</div>
</template>

<script>
export default {
name: 'About',
metaInfo: {
// 这里的 title 会替换 titleTemplate 中的字符占位
title: '关于我们'
}
}
</script>

 

如果想定义其他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) => {
// 设置title时 metaInfo 会同时更新
this.title = resp.title
this.description = resp.decription
})
}
}
}
</script>

 

这样就很轻松地完成了页面meta info的设定。

源作者:http://www.zhuyuwei.cn/2018/vue-meta-for-vuejs.html

转载于:https://www.cnblogs.com/iqiao/p/10439034.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值