useLocale.ts 1.9 KB
Newer Older
V
vben 已提交
1 2 3
/**
 * Multi-language related operations
 */
4
import type { LocaleType } from '/#/config';
V
vben 已提交
5

V
vben 已提交
6
import moment from 'moment';
V
vben 已提交
7

V
vben 已提交
8
import { i18n } from './setupI18n';
V
Vben 已提交
9
import { useLocaleStoreWithOut } from '/@/store/modules/locale';
V
Vben 已提交
10
import { unref, computed } from 'vue';
V
Vben 已提交
11
import { loadLocalePool, setHtmlPageLang } from './helper';
V
vben 已提交
12

13 14 15 16 17 18 19
interface LangModule {
  message: Recordable;
  momentLocale: Recordable;
  momentLocaleName: string;
}

function setI18nLanguage(locale: LocaleType) {
V
Vben 已提交
20 21
  const localeStore = useLocaleStoreWithOut();

22 23 24 25 26 27
  if (i18n.mode === 'legacy') {
    i18n.global.locale = locale;
  } else {
    (i18n.global.locale as any).value = locale;
  }
  localeStore.setLocaleInfo({ locale });
V
Vben 已提交
28
  setHtmlPageLang(locale);
29
}
V
vben 已提交
30 31

export function useLocale() {
V
Vben 已提交
32
  const localeStore = useLocaleStoreWithOut();
33 34 35
  const getLocale = computed(() => localeStore.getLocale);
  const getShowLocalePicker = computed(() => localeStore.getShowPicker);

V
Vben 已提交
36 37
  const getAntdLocale = computed((): any => {
    return i18n.global.getLocaleMessage(unref(getLocale))?.antdLocale ?? {};
38
  });
V
vben 已提交
39 40 41

  // Switching the language will change the locale of useI18n
  // And submit to configuration modification
42 43 44
  async function changeLocale(locale: LocaleType) {
    const globalI18n = i18n.global;
    const currentLocale = unref(globalI18n.locale);
V
Vben 已提交
45 46 47
    if (currentLocale === locale) {
      return locale;
    }
V
vben 已提交
48

49 50 51 52 53 54
    if (loadLocalePool.includes(locale)) {
      setI18nLanguage(locale);
      return locale;
    }
    const langModule = ((await import(`./lang/${locale}.ts`)) as any).default as LangModule;
    if (!langModule) return;
V
vben 已提交
55

56
    const { message, momentLocale, momentLocaleName } = langModule;
V
vben 已提交
57

58
    globalI18n.setLocaleMessage(locale, message);
V
vben 已提交
59
    moment.updateLocale(momentLocaleName, momentLocale);
60
    loadLocalePool.push(locale);
V
vben 已提交
61

62 63
    setI18nLanguage(locale);
    return locale;
V
vben 已提交
64 65
  }

V
vben 已提交
66 67
  return {
    getLocale,
68
    getShowLocalePicker,
V
vben 已提交
69
    changeLocale,
70
    getAntdLocale,
V
vben 已提交
71 72
  };
}