目标:每切换一个路由,title随之改变
首先 JS 中是通过document.title来获取title

如何传递 title - 通过路由配置中的 meta 来传递

(不使用路由传递,也可以使用全局的变量来传递)

  1. // router.ts
  2. const routes: Array<RouteConfig> = [
  3. {
  4. path: '/money',
  5. component: Money,
  6. meta: {
  7. title: "记账"
  8. }
  9. },
  10. ]

this.$route.meta来获取meta的数据

修改 title

  • 直接在生命周期中修改(不推荐,会有延迟,即使是使用beforeCreate
    1. // Money.vue
    2. beforeCreate(){
    3. document.title = this.$route.meta.title;
    4. }

    路由守卫(全局前置钩子中修改title

    如果meta中没有title就会是undefined,因此给了一个默认值
    1. // router.ts
    2. const defaultTitle: string = "mango"
    3. router.beforeEach((to, from, next) => {
    4. document.title = to.meta.title ? to.meta.title : defaultTitle
    5. next()
    6. })