useLocale.ts 1.6 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 { dateUtil } from '/@/utils/dateUtil';
V
vben 已提交
11

V
vben 已提交
12
import { i18n } from './setupI18n';
V
vben 已提交
13 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
    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;
        });

V
vben 已提交
37
        dateUtil.locale('cn');
V
vben 已提交
38 39 40 41 42 43
        break;
      // English
      case 'en':
        import('ant-design-vue/es/locale/en_US').then((locale) => {
          antConfigLocaleRef.value = locale.default;
        });
V
vben 已提交
44
        dateUtil.locale('en-us');
V
vben 已提交
45 46 47 48 49 50
        break;

      // other
      default:
        break;
    }
V
vben 已提交
51 52
  }

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

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