【问题标题】:Vue router optional first parameterVue路由器可选第一个参数
【发布时间】:2020-08-04 18:59:34
【问题描述】:

我有一个路线列表,它们都可以有一个可选的第一个参数。如果参数存在于 url 中,它将更改我在 api 调用中使用的标头。其他一切都保持不变。

与其创建两组路由来处理这个问题,有没有办法可以将第一个参数列为可选参数并且只定义一次路由?

对于所有路由,前面都可以有一个:environment 参数:

/:environment/:event_identifier/register/pages/:page_uuid

也可以是:

/:event_identifier/register/pages/:page_uuid

其他一切都将保持不变。

let routes = [{
   path: '/:event_identifier/register/pages/:page_uuid',
   name: 'ContentPage',
   component: ContentPage,
   meta: {
      requiresAuth: true,
   },
}, {
   path: '/:event_identifier/register/:pagenum',
   name: 'Register',
   component: Register,
   meta: {
      requiresAuth: true,
   },
}, {
   path: '/:event_identifier',
   name: 'Login',
   component: Login,
   children: [{
      path: '/:event_identifier/:registration_uuid/:pagenum',
      name: 'editRegistration',
      component: Login,
   }]
}]

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-router


    【解决方案1】:

    你可以像这样声明一个可选参数:

    path: '/myroute/:param?'
    

    :param 之后的 ? 使其成为可选参数,因此它将匹配不带参数的 http://domain/myroute 或带参数的 http://domain/myroute/25

    但是,我建议您在每条路线上设置可选参数 last。否则,你会得到一些不清楚的行为。想象一下,你有一个这样的路由路径,带有一个可选的第一个参数..

    path: '/myroute/:optional?/:notoptional'
    

    如果您访问 http://domain/myroute/25/10025 将匹配 :optional?

    但如果您访问 http://domain/myroute/2525 将匹配 :notoptional

    【讨论】:

      猜你喜欢
      • 2013-05-24
      • 2019-09-14
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 2020-07-03
      • 2021-06-28
      • 2015-02-25
      相关资源
      最近更新 更多