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 10 11 12 13

import moment from 'moment';

import 'moment/dist/locale/zh-cn';

V
vben 已提交
14
import { i18n } from './setupI18n';
V
vben 已提交
15 16

const antConfigLocaleRef = ref<any>(null);
V
vben 已提交
17 18

export function useLocale() {
V
vben 已提交
19 20 21 22 23
  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 已提交
24 25 26 27 28
    if (i18n.mode === 'legacy') {
      i18n.global.locale = lang;
    } else {
      ((i18n.global.locale as unknown) as Ref<string>).value = lang;
    }
V
vben 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
    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;
        });

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

      // other
      default:
        break;
    }
V
vben 已提交
53 54
  }

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

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