需求
1.不同路由路径下,动态更改title
2.相同路径下,像产品详情页,需要根据产品名字不同动态更改title
解决需求一
1.在router.js根据不同的路由配置所属title
{
path: '/startCertificate',
name: 'startCertificate',
component: startCertificate,
meta:{
title:'这是动态路由哦'
}
},
2.在main.js中配置
情况一:普通h5开发
router.beforeEach((to,from,next) =>{
// 路由发生变化修改页面title
if (to.meta.title) {
document.title = to.meta.title;
}
}
情况二:在app内嵌h5的混合应用中,iOS系统下部分APP的webview中的标题不能通过 document.title = xxx 的方式修改,因为在IOS webview中网页标题只加载一次,动态改变是无效的,解决代码如下
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)
}
}
});
解决需求二
1.安装依赖:npm i vue-wechat-title
2.在main.js中配置:
import VueWechatTitle from 'vue-wechat-title'
Vue.use(VueWechatTitle)
3.在需要改变title的vue文件中:
<template>
<div class="customerCaseDetail" v-wechat-title="changeTitle">
</div>
</template>
<script>
export default {
data() {
return {
changeTitle:''
}
},
created() {
this.changeTitle = '动态title'
},
}
</script>