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

本小妞迷上赌 提交于 2020-01-02 06:55:32

问题


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?


回答1:


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

});


来源:https://stackoverflow.com/questions/50321530/prefix-routes-with-locale-in-vue-js-using-vue-i18n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!