简体   繁体   English

使用 vue-i18n 从 API 服务器获取 JSON 对象的 Vue.js 中的国际化

[英]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.现在我正在 Vue.js 中构建一个支持多种语言的应用程序。 And I implemented internationalization using https://kazupon.github.io/vue-i18n .我使用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 ).我想将 i18n 中的获取消息部分从项目中的静态 JSON 文件更改为 API 调用结果(axios、ajax、Vuex ...等)。

How could I get JSON message files from API server and support dynamic multi language service??如何从 API 服务器获取 JSON 消息文件并支持动态多语言服务?

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
}

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.您可以从那里修改为您的 API 调用。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM