最终效果
页面变化时,页面标题也会随之变化
1、注册meta信息
进入router中的index.js,在每一个路由中配置meta信息
import Index from '~/pages/index.vue'
import Login from '~/pages/login.vue'
import NotFound from '~/pages/404.vue'
const routes=[
{
path:'/',
name:Index,
component:Index,
meta:{
title:'后台首页'
}
},
{
path: '/login',
name:Login,
component:Login,
meta:{
title:'登录页'
}
},
{
path: '/:pathMatch(.*)*',
name:NotFound,
component:NotFound,
meta:{
title:'404'
}
}
]
export const router = createRouter({
history: createWebHashHistory(),
routes
})
2、全局前置守卫设置页面标题
在全局前置守卫中可以通过to.meta.title拿到对应的标题信息
import {router} from '~/router'
router.beforeEach(async(to, from, next) => {
const title = (to.meta.title ? to.meta.title : '') + '-商城后台'
document.title = title
})
3、修改index.html中的title
上述步骤完成后,在刷新的时候会出现意想不到的情况,这是因为index.html中的title是固定的,因此你可以修改这个title,这样在刷新的时候不会显的那么突兀
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>商城后台</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.js"></script>
</body>
</html>