目标:每切换一个路由,title随之改变
首先 JS 中是通过document.title来获取title的
如何传递 title - 通过路由配置中的 meta 来传递
(不使用路由传递,也可以使用全局的变量来传递)
// router.tsconst routes: Array<RouteConfig> = [{path: '/money',component: Money,meta: {title: "记账"}},]
修改 title
- 直接在生命周期中修改(不推荐,会有延迟,即使是使用
beforeCreate)// Money.vuebeforeCreate(){document.title = this.$route.meta.title;}
路由守卫(全局前置钩子中修改
如果title)meta中没有title就会是undefined,因此给了一个默认值// router.tsconst defaultTitle: string = "mango"router.beforeEach((to, from, next) => {document.title = to.meta.title ? to.meta.title : defaultTitlenext()})
