Vue项目中,通过在路由的index.js文件中添加路由守卫beforeEach,可以实现在每次跳转页面时动态设置window.document.title为当前页面的标题。首先创建并导出路由器实例,然后在beforeEach钩子中更新标题,确保代码位于createRouter和export default router之间。每个子路由需配置meta属性,包含页面标题。这样,每个子路由切换时,浏览器标题将随之更新。
一、router —> index.js
import { createRouter, createWebHashHistory } from 'vue-router'
const router = createRouter({
history: createWebHashHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'login',
component: () => import('../views/Login/index.vue')
},
{
path: '/map',
name: 'map',
meta: { title: '地图' },//子路由页的标题添加meta属性
component: () => import('../views/map/index.vue')
},
]
})
router.afterEach(to => {
// 获取匹配的路由记录,倒序查找最近的 title
const nearestWithTitle = to.matched
.slice()
.reverse()
.find(r => r.meta?.title)
// 设置标题或使用默认值
document.title = nearestWithTitle?.meta.title || '产品应用' //没有meta,就默认展示'产品应用'
})
export default router
二、添加 meta 属性
设置每个子路由页的标题即可,在每个子路由对象中添加 meta 属性:
{
path: '/map',
name: 'map',
meta: { title: '地图' },//子路由页的标题添加meta属性
component: () => import('../views/map/index.vue')
}


上图就是不同路由路径展示了不同的title。

1万+

被折叠的 条评论
为什么被折叠?



