单页应用动态设置页面title

时间:2024-04-08 21:06:50

1.适用场景:所有通过router路由的单页应用。

2.示例代码:本文以vue-router为例。

 在router.js中:

let router = new Router({
routes: [
{
path: '/',
title: '',
redirect: '/chooseCity'
},
{
path: '/login',
title: '',
component: resolve => require(['components/login/login.vue'], resolve)
},
{
path: '/register',
title: '',
component: resolve => require(['components/login/register.vue'], resolve)
},
{
path: '/updatePassword',
title: '',
component: resolve => require(['components/login/updatePassword.vue'], resolve)
},
{
path: '/home',
title: '',
component: resolve => require(['components/home/home.vue'], resolve)
},
{
path: '/user',
title: '',
component: resolve => require(['components/user/user.vue'], resolve)
},
{
path: '/orderList',
title: '',
component: resolve => require(['components/orderList/orderList.vue'], resolve)
},
{
path: '/order',
title: '',
component: resolve => require(['components/order/order.vue'], resolve)
},
{
path: '/orderDetail',
title: '',
component: resolve => require(['components/orderDetail/orderDetail.vue'], resolve)
},
{
path: '/pay',
title: '',
component: resolve => require(['components/pay/pay.vue'], resolve)
},
{
path: '/chooseCinema',
title: '',
component: resolve => require(['components/chooseCinema/chooseCinema.vue'], resolve)
},
{
path: '/serviceRule',
title: '',
component: resolve => require(['components/serviceRule/serviceRule.vue'], resolve)
},
{
path: '/chooseCity',
title: '',
component: resolve => require(['components/chooseCity/chooseCity.vue'], resolve)
}
],
mode: 'history',
base: '/order/'
});
router.afterEach((transition) => {
// let name = transition.name;
// let item = router.options.routes.filter((ele) => { return ele.name === name; });
Tool.setTitle('哈哈哈哈');
});
export default router; 3.需要用到工具Tool.setTitle:
/**
* 设置页面标题
*/
function setTitle(title) {
document.title = title
var mobile = navigator.userAgent.toLowerCase();
if (/iphone|ipad|ipod/.test(mobile)) {
var iframe = document.createElement('iframe');
iframe.style.display = 'none'
var iframeCallback = function () {
setTimeout(function () {
iframe.removeEventListener('load', iframeCallback);
document.body.removeChild(iframe);
}, 0);
}
iframe.addEventListener('load', iframeCallback);
document.body.appendChild(iframe);
}
}