vue开发的单页面应用,需要在进入不同路由时动态改变title
- vue-cli 3 构建的项目
1.修改public>index.html
修改title标签id为:public_title,后面在路由钩子拦截预处理时会用到
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title id="public_title">xxx系统</title>
</head>
<body>
<noscript>
<strong>We're sorry but website doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
</body>
</html>
2.routes配置增加meta.pagetitle信息
routes: [
{
path: '/error404',
name: 'error404',
meta: {
pagetitle: '404 Error'
},
component: import('@/views/common/error-page-404.vue')
}
]
3.路由钩子拦截,预处理统一设置title
用到Vue路由钩子:beforeEach,通过对象to获取到即将进入的路由的标题(meta.pagetitle),document.getElementById(‘public_title’).innerHTML动态修改标题
/**
* 全局路由钩子
* to: 将要进入的,路由对象
* from:正要离开,路由对象
*/
router.beforeEach((to, from, next) => {
document.getElementById('public_title').innerHTML = to.meta.pagetitle === undefined ? 'xxx系统' : to.meta.pagetitle
next();
})