Reputation: 189
I know its kind of basic but i cant find the best practice for this one in Vue.js.
I'm using Vue Cli 3 and need to get a few routes pointing to the same Home page in the app.
Basically it should be an affiliate number as a parameter - or no affiliate at all.
So what i did is , in the router.js - giving 2 different paths to the same home component :
{
path: '/',
name: 'home',
component: Home
},
{
path: '/affId=:affiliateNumber?',
name: 'home',
component: Home
},
This code is working , but obviously not a goood solution as i also get this warning - '[vue-router] Duplicate named routes definition'
what is the best way to get it done ?
many thanks.
Upvotes: 1
Views: 193
Reputation: 3907
You get the error just because you're using the same name
(home) for both routes. You might adjust these to e. g. home
and home-2
or whatever. Best practice would be to only use 1 single route and adjust the parameters and query accordingly.
In your example you are using wrong route mapping. A query param should never follow a slash. Instead, it should always be attended to the current route by a ?
.
Depending on your use-case you can simplify your routes. If you need to access a URL parameter you cold use a route like this:
{
path: '/:affiliateNumber',
name: 'home',
component: Home
},
You'll be able to access :affiliateNumber
whenever you need in your code. this could also be a child route and the parent could be path: '/'
.
However, in your case it should be enough to just use a query param. Doing so you don't have to care about child routes or anything else because query params are always optional. That said you could leave your route just like this...
{
path: '/',
name: 'home',
component: Home
},
... and append any query param you want by just using /home?affId=123
.
Upvotes: 2