手机版 收藏 导航

在 Vue Router 中如何设置页面标题

原创   www.link114.cn   2024-02-11 08:48:11

在 Vue Router 中如何设置页面标题

在路由配置中为每个路由添加一个 meta 属性,用于存储页面标题信息。例如:

const routes = [
  {
    path: '/',
    name: 'Home',
    meta: {
      title: '首页'
    }
  },
  {
    path: '/about',
    name: 'About',
    meta: {
      title: '关于我们'
    }
  }
]

接下来,在 main.js 中使用 router.beforeEach 导航钩子函数,在路由切换时设置页面标题。

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title
  }
  next()
})

这样,当路由切换时,页面标题会自动更新为对应路由的 title 值。

页面标题需要更复杂的逻辑,比如根据用户角色动态设置,可以考虑将页面标题信息存储在 Vuex 中,在导航钩子函数中读取并设置。这样可以更好地管理页面标题的状态。