TransWikia.com

Vue router optional first parameter

Stack Overflow Asked by user7531085 on December 18, 2021

I have a list of routes that can all have an optional first parameter. If the parameter is present in the url, it will change a header I use in my api calls. Everything else remains the same.

Rather than create two sets of routes to handle this, is there a way I can list the first parameter as optional and only define my routes once?

For all routes, there can be an :environment param present in the front:

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

or it can be:

/:event_identifier/register/pages/:page_uuid

Everything else will remain the same.

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,
   }]
}]

One Answer

You can declare an optional param like this:

path: '/myroute/:param?'

The ? after :param makes it optional, so it will match http://domain/myroute with no param or http://domain/myroute/25 with a param.

But, I would suggest making your optional params last on each route. Otherwise, you get some unclear behavior. Imagine you had a route path like this with an optional first param..

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

If you visit http://domain/myroute/25/100, the 25 would match :optional?

But if you visit http://domain/myroute/25, the 25 would match :notoptional

Answered by Dan on December 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP