Vue:单页面应用动态设置title

vue开发的单页面应用,需要在进入不同路由时动态改变title

  • vue-cli 3 构建的项目

1.修改public>index.html

修改title标签id为:public_title,后面在路由钩子拦截预处理时会用到

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title id="public_title">xxx系统</title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but website doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

2.routes配置增加meta.pagetitle信息

routes: [
    {
      path: '/error404',
      name: 'error404',
      meta: {
        pagetitle: '404 Error'
      },
      component: import('@/views/common/error-page-404.vue')
    }
  ]

3.路由钩子拦截,预处理统一设置title

用到Vue路由钩子:beforeEach,通过对象to获取到即将进入的路由的标题(meta.pagetitle),document.getElementById(‘public_title’).innerHTML动态修改标题

/**
 * 全局路由钩子
 * to: 将要进入的,路由对象
 * from:正要离开,路由对象
 */
router.beforeEach((to, from, next) => {
  document.getElementById('public_title').innerHTML = to.meta.pagetitle === undefined ? 'xxx系统' : to.meta.pagetitle
  next();
})
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值