import Vue from 'vue'
|
import VueI18n from 'vue-i18n'
|
import store from '@/store';
|
|
import elementEnLocale from 'element-ui/lib/locale/lang/en'
|
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'
|
|
import Base from '@/assets/js/i18n/base';
|
import router from '@/router/i18n';
|
|
const messages = {
|
US: {
|
...elementEnLocale,
|
...Base.US,
|
...router.US,
|
},
|
CN: {
|
...elementZhLocale,
|
...Base.CN,
|
...router.CN,
|
}
|
};
|
// const LANGS = ['US', 'CN'];
|
|
/**
|
* 创建 i18n 配置
|
* @param locale 本地化语言
|
* @param fallback 语言
|
* @returns {VueI18n}
|
*/
|
function initI18n(locale, fallback) {
|
Vue.use(VueI18n)
|
let i18nOptions = {
|
locale,
|
messages,
|
fallbackLocale: fallback,
|
silentFallbackWarn: true,
|
}
|
return new VueI18n(i18nOptions)
|
}
|
|
/**
|
*
|
* @param {*} msgObj 主要的语言包
|
* @param {*} msgOtherList [[msgObj, nameSpace]]其他语言包数组
|
* @returns
|
*/
|
function createI18nOption(msgObj, msgOtherList) {
|
let msg = JSON.parse(JSON.stringify(messages));
|
if (msgOtherList && Object.prototype.toString.call(msgOtherList) === '[object Array]') {
|
msgOtherList.forEach((v) => {
|
let {CN, US} = v[0].messages;
|
let nameSpace = v[1];
|
msg.US[nameSpace] = US;
|
msg.CN[nameSpace] = CN;
|
});
|
}
|
return {
|
i18n: {
|
messages: msgObj.messages,
|
sharedMessages: msg,
|
},
|
// watch: {
|
// "$store.state.settings.lang": {
|
// handler(v) {
|
// this.$i18n.locale = v;
|
// this.$root.$i18n.locale = v;
|
// // console.log('mixin===', msgObj)
|
// },
|
// immediate: true
|
// },
|
// },
|
}
|
}
|
|
const translate = (localeKey) => {
|
const locale = store.state.settings.lang;
|
const i18n = Vue.prototype.$$i18n;
|
const hasKey = i18n.te(localeKey, locale);
|
const translatedStr = i18n.t(localeKey);
|
if (hasKey) {
|
return translatedStr;
|
}
|
return localeKey;
|
}
|
|
export {
|
initI18n,
|
messages,
|
createI18nOption,
|
translate,
|
}
|