Prefix routes with locale in vue.js (using vue-i18n)

Victor picture Victor · May 14, 2018 · Viewed 11.2k times · Source

I have a locale.js file which is responsible for defining user locale. Here it is:

import store from '@/vuex/index'

let locale

const defaultLocale = 'en_US'

if (store.getters['auth/authenticated']) {
  locale = store.getters['auth/currentUser'].locale || defaultLocale
} else {
  if (localStorage.getItem('locale')) {
    locale = localStorage.getItem('locale')
  } else {
    locale = defaultLocale
  }
}

export default locale

Also I have a i18n.js file which is responsible for making i18n instance which I use when I init my app.

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import locale from '@/services/locale'

Vue.use(VueI18n)

const fallbackLocale = 'en_US'

let i18n = new VueI18n({
  locale,
  fallbackLocale,
})

i18n.setLocaleMessage('ru_RU', require('@/lang/ru_RU.json'))
i18n.setLocaleMessage('en_US', require('@/lang/en_US.json'))

export { i18n }

Now I think that it'd be more convenient to have URLs prefixed with locale, like /en/profile or /ru/profile. This way I can share a link with locale which would be already set.

Not sure how do to this though. Making all routes child and put /:locale? is not that convenient because router is not yet initialized (I pass i18n and router instances simultaneously when initing root app instance).

How can I achieve that, what would be the best approach?

Answer

ittus picture ittus · May 14, 2018

You can implement router

routes: [{
    path: '/:lang',
    children: [
      {
        path: 'home'
        component: Home
      },
      {
        path: 'about',
        component: About
      },
      {
        path: 'contactus',
        component: ContactUs
      }
    ]
  }]

and set locale in beforeEach hook

// use beforeEach route guard to set the language
router.beforeEach((to, from, next) => {

  // use the language from the routing param or default language
  let language = to.params.lang;
  if (!language) {
    language = 'en';
  }

  // set the current language for vuex-i18n. note that translation data
  // for the language might need to be loaded first
  Vue.i18n.set(language);
  next();

});