useLocale.ts 1.8 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 { i18n } from './setupI18n';
V
Vben 已提交
7
import { useLocaleStoreWithOut } from '/@/store/modules/locale';
V
Vben 已提交
8
import { unref, computed } from 'vue';
V
Vben 已提交
9
import { loadLocalePool, setHtmlPageLang } from './helper';
V
vben 已提交
10

11 12
interface LangModule {
  message: Recordable;
V
vben 已提交
13 14
  dateLocale: Recordable;
  dateLocaleName: string;
15 16 17
}

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

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

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

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

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

47 48 49 50 51 52
    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 已提交
53

V
vben 已提交
54
    const { message } = langModule;
V
vben 已提交
55

56 57
    globalI18n.setLocaleMessage(locale, message);
    loadLocalePool.push(locale);
V
vben 已提交
58

59 60
    setI18nLanguage(locale);
    return locale;
V
vben 已提交
61 62
  }

V
vben 已提交
63 64
  return {
    getLocale,
65
    getShowLocalePicker,
V
vben 已提交
66
    changeLocale,
67
    getAntdLocale,
V
vben 已提交
68 69
  };
}