I have an optional lang
parameter at the beginning of all my routes paths like /:lang?/foo
.
When I use the foo route in the router-link
passing the lang
param it matches that route and properly adds a .router-link-active
class to the <a/>
.
However in many places of my project I've passed no params to the router-link
and in the global router navigation guard beforeEach
I'm setting the lang
param if no one is passed. In this case, router-link
won't add the active class since it doesn't match the route because the missing param in the to
prop.
How can I make the matching logic ignore that optional param for all routes so I have the .router-link-active
and .router-link-exact-active
classes added?
Here is a jsfiddle I played with where I want the first link to be red.
Bellow are the relevant parts:
<router-link :to="{name: 'foo'}">/foo</router-link>
<router-link :to="{name: 'foo', params: {lang: 'en'}}">/en/foo</router-link>
routes: [
{
path: '/:lang?',
component: {
render(c) {
return c('router-view');
},
},
children: [
{
name: 'foo',
path: 'foo',
component: Foo
}
]
}
]
router.beforeEach((to, from, next) => {
if (!to.params.lang) {
const route = { ...to };
route.params = { ...route.params, lang: 'en'};
next(route);
} else {
next();
}
});