useLocale.ts 1.5 KB
Newer Older
V
vben 已提交
1 2 3
/**
 * Multi-language related operations
 */
V
vben 已提交
4
import type { LocaleType } from '/@/locales/types';
V
vben 已提交
5
import type { Ref } from 'vue';
V
vben 已提交
6 7

import { unref, ref } from 'vue';
V
vben 已提交
8
import { useLocaleSetting } from '/@/hooks/setting/useLocaleSetting';
V
vben 已提交
9

V
vben 已提交
10
import { i18n } from './setupI18n';
V
vben 已提交
11

V
vben 已提交
12
import 'moment/dist/locale/zh-cn';
V
vben 已提交
13

V
vben 已提交
14
const antConfigLocaleRef = ref<any>(null);
V
vben 已提交
15 16

export function useLocale() {
V
vben 已提交
17 18 19 20 21
  const { getLang, getLocale, setLocale: setLocalSetting } = useLocaleSetting();

  // Switching the language will change the locale of useI18n
  // And submit to configuration modification
  function changeLocale(lang: LocaleType): void {
V
vben 已提交
22 23 24 25 26
    if (i18n.mode === 'legacy') {
      i18n.global.locale = lang;
    } else {
      ((i18n.global.locale as unknown) as Ref<string>).value = lang;
    }
V
vben 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
    setLocalSetting({ lang });
    // i18n.global.setLocaleMessage(locale, messages);

    switch (lang) {
      // Simplified Chinese
      case 'zh_CN':
        import('ant-design-vue/es/locale/zh_CN').then((locale) => {
          antConfigLocaleRef.value = locale.default;
        });

        break;
      // English
      case 'en':
        import('ant-design-vue/es/locale/en_US').then((locale) => {
          antConfigLocaleRef.value = locale.default;
        });
        break;

      // other
      default:
        break;
    }
V
vben 已提交
49 50
  }

V
vben 已提交
51
  // initialization
V
vben 已提交
52
  function setLocale() {
V
vben 已提交
53 54
    const lang = unref(getLang);
    lang && changeLocale(lang);
V
vben 已提交
55 56
  }

V
vben 已提交
57
  return {
V
vben 已提交
58
    setLocale,
V
vben 已提交
59 60 61 62 63 64
    getLocale,
    getLang,
    changeLocale,
    antConfigLocale: antConfigLocaleRef,
  };
}