Internationalization in Vue.js using vue-i18n getting JSON Object from API server

YOUNG MIN CHO picture YOUNG MIN CHO · Apr 17, 2019 · Viewed 7.1k times · Source

Now I'm building an app in Vue.js supports multiple Languages. And I implemented internationalization using https://kazupon.github.io/vue-i18n.

I want to change getting message part in i18n from static JSON file in a project to API call result(axios, ajax, Vuex ...etc ).

How could I get JSON message files from API server and support dynamic multi language service??

Any ideas? Thanks in advance!

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import EN from '@/COMMON/i18n/en.json'
import KO from '@/COMMON/i18n/ko.json'
import store from '@/COMMON/store/store'

Vue.use(VueI18n)


const i18n = new VueI18n({
    locale: sessionStorage.LANG_CD,
    fallbackLocale: 'ko',
    silentTranslationWarn: true,
    messages: {
        en: EN,
        ko: KO
        // option 1. ko: axios ... some code 
        // option 2. ko: store.getters ... some code
    },
  });

export default {
    i18n
}

Answer

User 28 picture User 28 · Apr 17, 2019

Please see Lazy loading translations.

In the document, It uses dynamic importing to import new translation files. You can modify from there to your API call instead.

Example:

// i18n-setup.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import axios from 'axios'

Vue.use(VueI18n)

export const i18n = new VueI18n({
  locale: 'en',
  fallbackLocale: 'en'
})

const loadedLanguages = []

function setI18nLanguage (lang) {
  i18n.locale = lang
  axios.defaults.headers.common['Accept-Language'] = lang
  document.querySelector('html').setAttribute('lang', lang)
  return lang
}

export function loadLanguageAsync (lang) {
  if (loadedLanguages.includes(lang)) {
    if (i18n.locale !== lang) setI18nLanguage(lang)
    return Promise.resolve()
  }
  return axios.get(`/api/lang/${lang}`).then(response => {
    let msgs = response.data
    loadedLanguages.push(lang)
    i18n.setLocaleMessage(lang, msgs.default)
    setI18nLanguage(lang)
  })
}

// router.js
router.beforeEach((to, from, next) => {
  const lang = to.params.lang
  loadLanguageAsync(lang).then(() => next())
})