vue3+ts,使用全局路由前置守卫给页面title设置meta.title

直接上封装ts代码

const setTitle = (router: any)=> {
  router.beforeEach((to: any, from: unknown, next: Function)=> {
    window.document.title = (to.meta.title || '员工宝') as string
    next()
  })
}

export default {
  setTitle,
}

路由页面调用

import { title } from '/title'

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/home/HomeIndex.vue'),
    meta: {
      title: '首页',
    }
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_APP_NAME),
  routes
})


// 动态title
title.setTitle(router)

export default router

猜你喜欢

转载自blog.csdn.net/m0_64207574/article/details/129479203