如何根据 Vue 路由器参数设置页面标题?

问题描述 投票:0回答:2

我正在尝试使页面标题(元标记)显示您当前所在的个人资料的用户名。我的代码如下:

export default new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/profile/:userId/",
      name: "profile",
      component: Profile,
      meta: {
        title: "Profile - ((USERID HERE))", // <-- Find how to insert :userId into page title
      },
    },

我怎样才能做到这一点?使用 vue router 可以有动态页面标题吗?

vue.js vue-router
2个回答
2
投票

您可以使用 router props 作为函数, 因此,不要传递

userId
的 prop,而是传递
title
的 prop,如下所示:

routes: [
    {
      path: "/profile/:userId",
      name: "profile",
      component: Profile,
      props: route => ({ title: `Profile ${route.params.userId}` })
    },
]

您可以在 vue 文档

中阅读更多相关信息

1
投票

您需要在每个路由器条目上设置标题

const router = new Router({
  mode: "history",
  base: process.env.BASE_URL,
  routes: [
    {
      path: "/profile/:userId/",
      name: "profile",
      component: Profile,
      meta: {
        title: "Profile - ((USERID HERE))", // <-- Find how to insert :userId into page title
      },
    },
//Other properties
})

router.beforeEach((to, from, next) => {
 // You have access to the route here so you could dynamically get the variable? to.params? (Sorry for editing this post as didn't see the full question!)

 document.title = to.meta.title ? to.meta.title : "Some Default Title"

 // Edit 2 it seems params contains the thing you need so you could detect if to.meta.title is a thing and dynamically change it `Profile - (${to.params.userId})`
 next() // You must call next!
})

export default router
© www.soinside.com 2019 - 2024. All rights reserved.