第一种:适用于在已经定义好title的情况下,例如首页,关于页等等
1.1 main.js
const defaultTitle = ‘默认 title‘ router.beforeEach((to, from, next) => { document.title = to.meta.title ? to.meta.title : defaultTitle next() })
1.2 index.js
routes: [ { name:‘home‘, path: ‘/home/:openname‘, component: Home, meta: { title: ‘首页‘ } } ]
第二种:vue-meta 插件(适用于无法固定title的情况下,例如文章页)
2.1 安装
npm install vue-meta --save
2.2 在main.js引入
import Meta from ‘vue-meta‘
Vue.use(Meta)
2.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‘ } ] } }
2.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>
第三种:vue-wechat-title
3.1 安装
npm install vue-wechat-title --save
3.2 在main.js中引入
import VueWechatTitle from ‘vue-wechat-title‘
Vue.use(VueWechatTitle)
3.3 使用
在router>index.js中添加meta对象配置title
const router = new Router({
routes: [
...
{
path: "/gameDesc",
name: ‘gameDesc‘,
component: resolve => import(‘@/pages/Game/gameDesc‘),
meta:{
title: ‘游戏说明‘
}
},
{
path: "/integralList",
name: ‘integralList‘,
component: resolve => import(‘@/pages/Game/integralList‘),
meta:{
title: ‘积分收取记录‘
}
}
...
]
});
router.afterEach(route => {
// 从路由的元信息中获取 title 属性
if (route.meta.title) {
document.title = route.meta.title;
// 如果是 iOS 设备,则使用如下 hack 的写法实现页面标题的更新
if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
const hackIframe = document.createElement(‘iframe‘);
hackIframe.style.display = ‘none‘;
hackIframe.src = ‘/static/html/fixIosTitle.html?r=‘ + Math.random();
document.body.appendChild(hackIframe);
setTimeout(_ => {
document.body.removeChild(hackIframe)
}, 300)
}
}
});
export default router;
在App.vue中修改router-view
<router-view v-wechat-title=‘$route.meta.title‘></router-view>
原文:https://www.cnblogs.com/woniu666/p/13338425.html