BT101
BT101

Reputation: 3826

Get id from URL on alias in vue2

I have one route which should support 2 different URLs - /settings/:code and /settings:

{
    path: '/settings',
    alias: '/settings/:code',
    name: 'settings',
    component: settings
},

It is working correctly in my SPA when I go to URL localhost:8080/settings and localhost:8080/settings/123 in both way it's hitting settings component.

How ever when I try to get this :code like this:

resetCode: this.$route.params.code,

from url it is always undefined even when I'm on localhost:8080/settings/123.

When I turn alias and path the other way around so it's:

{
    alias: '/settings',
    path: '/settings/:code',
    name: 'settings',
    component: settings
},

then my :code is correct, I mean it's 123 when I go to URL localhost:8080/settings/123 but in this case it's not displaying settings component when I go to url localhost:8080/settings.

So either way is bad, how I can fix it?

Upvotes: 4

Views: 1644

Answers (2)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

This is not how alias works. You can specify url alias with different names but not with url parameters.

path: '/settings'
alias: '/settings/:code' // incorrect
alias: '/settingsAlias' // correct (different path name)

path: '/settings/:code'
alias: '/settings' // incorrect ( param is missing )
alias: '/settingsAlias/:code' // correct
alias: '/settingsAlias/:codeAlias // correct

Also, the @Thomas Kleßen answer seems to be working fine for you. But this is not why child routes are created for.

path: '/settings',
component: settings,
children: [
  {
    path: ':code' // ( incorrect usage ) how is this children?
  }
]

Child routes should follow with a slash / (and not just /:param but /pathname ). If you use as preceding example, then you're just doing a trick with the router.

Then, what is the correct way of using it?

Well, you can define an optional paramter:

path: '/settings/:code?' // using ? defines param as optional

So, now you can hit '/settings' or '/settings/123' in the url.

Upvotes: 3

Thomas
Thomas

Reputation: 2536

Try this:

{
    name: 'settings',
    path: '/settings',
    component: settings,
    children: [
      {
        name: 'settings_code',
        path: ':code',
        component: settings
      }
    ]
}

It is untested, but i think because your alias and path match the same path your problem occurs. That's why i suggest to try it with a child-route.

Upvotes: 2

Related Questions