Routing meta information implements the dynamic title of the App

Using the routing metainformation provided by VueRouter, you can easily implement dynamic changes in the App title, as shown below:

 

First attach the official link  routing meta information | Vue Router

Let’s talk about the implementation ideas:

1. When defining a route, configure the meta field

const router = createRouter({
  routes: [
    {
      ...
      children: [
        {
          path: '/home',
          name: 'home',
          component: () => import('@/views/home/index.vue'),
          meta: { title: '首页' }
        },
        {
          path: '/article',
          name: 'article',
          component: () => import('@/views/article/index.vue'),
          meta: { title: '健康百科' }
        },
        {
          path: '/notify',
          name: 'notify',
          component: () => import('@/views/notify/index.vue'),
          meta: { title: '消息中心' }
        },
        {
          path: '/user',
          name: 'user',
          component: () => import('@/views/user/index.vue'),
          meta: { title: '个人中心' }
        }
      ]
    }
  ]
})

2. In the global post-navigation guard, implement switching route settings title

        An error will appear in the TypeScript environment

# 全局后置导航守卫
router.afterEach((to) => {
  # 报错: 不能将类型“unknown”分配给类型“string”
  document.title = to.meta.title
})

3. The official article gives us a way to solve TS error reports by extending the RouteMeta interface to enter the meta field.

# src / types 文件夹下 / 新建 vue-router.d.ts 类型声明文件
import 'vue-router'

declare module 'vue-router' {
  interface RouteMeta {
    // 可选的
    title?: string
  }
}

4. New error message appears

        When extending the RouteMeta interface, we set optional parameters, so to.meta.title may indeed be undefined.

        Setting required parameters is not considered here unless you want to set all interface types under Route!

router.afterEach((to) => {
  # 不能将类型“string | undefined”分配给类型“string”
  document.title = to.meta.title
})

To solve the new error:

router.afterEach((to) => {
  document.title = to.meta.title || '缺省标题'
})

Done!

End-----------------------------

Guess you like

Origin blog.csdn.net/u011690675/article/details/130222448