vue-router 如何在跳转的时候动态设置meta

先说目标,为了实现tab的名字与真实业务名称关联
image.png

例如一个详情页的路由定义如下

{
    path: "/knowledge/private/detail/:id",
    meta: {
        title: "个人知识"
    },
    component: () => import("......")
},

其中id为具体的业务id,想实现点击某个知识(比如:系统介绍),跳转到详情页面,并且document.title和tab的名字显示为个人知识-系统介绍,即原来的meta.title+具体知识的名称。

现在tab组件中,是通过route的meta.title取值来实现的。因为router.push无法传递meta,只能通过query来传动态的title,但是这样又会将title显示在浏览器地址栏中,而使用params又不能满足可以刷新。

router.push({
    path: "/knowledge/private/detail/" + row.id,
    query: {
         isEdit: true,
         title: row.name
    }
});

请问有没有什么其他办法可以解决,如果在router.push的时候就可以传参title的话最好,代码量最少,(不考虑通过vuex、emit、inject之类的)

阅读 15.8k
4 个回答

全局的 路由导航守卫 beforeEach, 统一根据路由 改变 document.title可以吗

可以试试通过配置二级路由的方式

可以试试配置路由解耦来传参,使用params隐藏地址栏参数,这样刷新params也还在
路由配置:

{
    path: "/knowledge/private/detail/:id/:title",
    meta: {
        title: "系统介绍"
    },
    props: true,
    component: () => import("......")
},

router.push({

name: "子组件name名",
params: {
     isEdit: true,
     id: row.id,
     title: row.name
}

});

子组件页面:

 props: {
            id: {
                type: String
            },
            title: {
                type: String
            }
        },

然后就可以随意取用

补:
另一种方法 把params存在localstorage中
跳转使用params
然后使用路由守卫

router.beforeEach((to, from, next) => {
     localStorage.setItem('routerParams', JSON.stringify(to.params));
     next()
});

子组件页面:

getParams() {
  return JSON.parse(localStorage.getItem('routerParams'))
}
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    // 自己拼格式 改变document.title
    document.title = to.meta.title + ' - ' + Config.title
  }

})
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题