Vue 单页应用 动态修改页面 title
使用 Vue + VueRouter 开发单页应用时,有些需要修改页面 title 的场景,可以通过在 router 中添加 meta 元信息来实现:routes: [{name: 'home',path: '/home/:openname',component: Home,meta: {title: '首页'}}]添...
·
使用 Vue + VueRouter 开发单页应用时,有些需要修改页面 title 的场景,可以通过在 router 中添加 meta 元信息来实现:
routes: [{
name: 'home',
path: '/home/:openname',
component: Home,
meta: {
title: '首页'
}
}]
添加完 meta 信息后,还需要在路由跳转后的回调中获取当前页的 title,并赋值给 document.title:
router.afterEach((to, from, next) => {
/* 路由发生变化修改页面 title */
if (to.meta.title) {
document.title = to.meta.title;
}
next();
})
上述做法在某些 IOS 的浏览器或 web-view 中无法生效,所以需要想办法解决 IOS 下的兼容问题,可以利用 iframe 节点的插入和删除实现兼容,具体做法如下:
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 = '/path/fixIosTitle.html?r=' + Math.random();
document.body.appendChild(hackIframe);
setTimeout(() => {
document.body.removeChild(hackIframe)
}, 300)
}
}
});
其中“fixIosTitle.html”是一个空的.html文件,仅用作一个新的 iframe,供插入、删除使用。
如此一来,在 IOS 设备下也能动态改变页面 title 了,是不是很好的体验呢~
更多推荐
已为社区贡献2条内容
所有评论(0)