vue3使用路由元信息meta实现动态页面标题

最终效果
页面变化时,页面标题也会随之变化
在这里插入图片描述
在这里插入图片描述
1、注册meta信息
进入router中的index.js,在每一个路由中配置meta信息

import Index from '~/pages/index.vue' 
import Login from '~/pages/login.vue' 
import NotFound from '~/pages/404.vue'

const routes=[
  {
    path:'/',
    name:Index,
    component:Index,
    meta:{
      title:'后台首页'
    }
  },
  {
    path: '/login',
    name:Login,
    component:Login,
    meta:{
      title:'登录页'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name:NotFound,
    component:NotFound,
    meta:{
      title:'404'
    }
  }
]

export const router = createRouter({
  history: createWebHashHistory(),
  routes
})

2、全局前置守卫设置页面标题
在全局前置守卫中可以通过to.meta.title拿到对应的标题信息

import {router} from '~/router'

router.beforeEach(async(to, from, next) => {
  const title = (to.meta.title ? to.meta.title : '') + '-商城后台'
  document.title = title
})

3、修改index.html中的title
上述步骤完成后,在刷新的时候会出现意想不到的情况,这是因为index.html中的title是固定的,因此你可以修改这个title,这样在刷新的时候不会显的那么突兀

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>商城后台</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值