Pierre
Pierre

Reputation: 13046

How to add an i18n locale prefix in Vue router for all the locales except for the default one?

I'm trying to create a route to add a locale prefix for all the routes, I got it working using this code:

routes: [{
  path: '/:lang',
  component: {
    template: '<router-view />'
  },
  children: [
    {
      path: '',
      name: 'home',
      component: Home
    },
    {
      path: 'about',
      name: 'about',
      component: About
    },
    {
      path: 'contact',
      name: 'contact',
      component: Contact
    }
  ]
}]

For the default locale en I don't want to set this prefix so params.lang is going to be the full path in this case and not the locale code, so requesting any path without a locale code will render the Home component which matches.

So how can I do this? Does a navigation guard like beforeEnter help in this case?

Upvotes: 4

Views: 3829

Answers (1)

maxim
maxim

Reputation: 626

Actually you can do it without navigation guards. The main goal here is to let the router understand when you have a url without :lang parameter. To distinguish between the language prefixes and the actual paths you could use a regex pattern for the :lang param like: (de|fr|en|zu) (whatever list of codes is suitable for you). And make the :lang to be an optional ?.

So something like this should work: path: '/:lang(de|fr|en|zu)?' At least it works for me :) ...

So now if you request /about or /de/about both would match About.. however the first one will have params.lang === undefined. So I guess whenever you set your locale you can do: const locale = this.$route.params.lang || 'en'

here is the documentation for Advanced Matching Patterns

routes: [{
  path: '/:lang(de|fr|en|zu)?',
  component: {
    template: '<router-view />'
  },
  children: [
    {
      path: '',
      name: 'home',
      component: Home
    },
    {
      path: 'about',
      name: 'about',
      component: About
    },
    {
      path: 'contact',
      name: 'contact',
      component: Contact
    }
  ]
}]

Upvotes: 5

Related Questions