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

Set page title dependent on Vue router params

我不确定这是否可行,但这里是:

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

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 路由器获得动态页面标题?谢谢

你可以使用路由器道具作为功能, 所以不是传递 userId 的道具,而是像这样传递 title 的道具:

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

您可以在 vue docs

中阅读更多相关信息

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

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