Vue项目如何动态设置路由meta信息中的title属性值

场景:编辑、新建页面配置为同一个路由信息,期望不同页面的文档title展示不一样。

目前的配置如下,不能实现需求。

 因此,我们需要动态的去设置meta的值。思路:借助Vue Router的路由独享守卫 beforeEnter 和 全局解析守卫 beforeResolve 或全局后置钩子 afterEach 实现。

 修改代码如下:

1. 具体路由对象配置

{
    path: 'template-operation/:id?/edit',
    beforeEnter: (to, from, next) => {
      if (to.params.id) {
        to.meta.title = '编辑模板作业'
      } else {
        to.meta.title = '新建模板作业'
      }
      next()
    },
    name: 'file-upload/template-operation/edit',
    component: TemplateEdit
  },

2.全局路由钩子配置

// 全局解析守卫
router.beforeResolve((to, from, next) => {
  window.document.title = to.meta.title
  next()
})

问题优雅的解决了。。。

参考:https://router.vuejs.org/zh/guide/

--------学习 交流 提升-----------
原文地址:https://www.cnblogs.com/blogNYGJ/p/14280494.html