Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
like image 413
YOUNG MIN CHO Avatar asked Apr 17 '19 07:04

YOUNG MIN CHO


People also ask

How do I add internationalization to my vue application?

To provide internationalization you have to tell Vue to use the vue-i18n plugin and provide it a messages object. The messages object will have the translations for every language your application supports.

What is internationalization in json?

json includes strings that are displayed to the user, such as the extension's name and description. If you internationalize these strings and put the appropriate translations of them in messages. json, then the correct translation of the string will be displayed to the user, based on the current locale, like so.


1 Answers

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())
})
like image 131
User 28 Avatar answered Oct 30 '22 20:10

User 28