如何修改页面标题
修改页面标题的方式有多种,本文选择使用 vueuse
。
参考文档:https://vueuse.org/core/useTitle/
安装
yarn add @vueuse/core
使用
import { useTitle } from '@vueuse/core'
const title = useTitle()
console.log(title.value) // print current title
title.value = 'Hello' // change current title
应用路由守卫修改页面标题
路由整个生命周期中存在多个守卫(具体参考:https://blog.csdn.net/gongm24/article/details/125844051)。
- 定义页面标题:每个页面拥有各自的标题,可以定义到路由的
meta
中。 - 触发时机:路由最终确定之后,使用
afterEach
守卫,其它守卫都不是终态,可能存在被拦截的可能。
定义页面标题
在 meta
中定义 title
属性
const routes = [{
path: "/",
name: 'Home',
component: () => import(/* webpackChunkName: "Home" */'@/views/Home.vue'),
meta: { title: '工作台' }
}]
通过路由守卫修改页面标题
appStore.title
是默认标题
router.afterEach((to) => {
// 设置网页标题,路由中 meta 必须设置 title
let subTitle = to.meta.title
if (isEmpty(subTitle)) {
title.value = appStore.title
} else {
title.value = subTitle + " - " + appStore.title
}
done()
})