he wei
2025-04-09 850af610b190eeabbd05eba3291fe359775676af
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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,
}