Answer a question

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();
  }
});

Answers

I got it by overriding the default vue router resolve method since it's also used in the router-link for finding route matches accordingly to the to route.

So this is the code that solved my problem:

import VueRouter from 'vue-router';

class Router extends VueRouter {
  resolve(to, current, append) {
    const route = { ...to };
    route.params = { ...route.params, language: 'en' };
    return super.resolve(route, current, append);
  }
}

Vue.use(Router);

const router = new Router({
  ...
})
Logo

Vue社区为您提供最前沿的新闻资讯和知识内容

更多推荐