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

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

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

const loadLocalePool: LocaleType[] = [];
V
vben 已提交
19

20 21 22 23
export function setHtmlPageLang(locale: LocaleType) {
  document.querySelector('html')?.setAttribute('lang', locale);
}

24 25 26 27
export function setLoadLocalePool(cb: (loadLocalePool: LocaleType[]) => void) {
  cb(loadLocalePool);
}

28
function setI18nLanguage(locale: LocaleType) {
V
Vben 已提交
29 30
  const localeStore = useLocaleStoreWithOut();

31 32 33 34 35 36
  if (i18n.mode === 'legacy') {
    i18n.global.locale = locale;
  } else {
    (i18n.global.locale as any).value = locale;
  }
  localeStore.setLocaleInfo({ locale });
37
  setHtmlPageLang(locale)
38
}
V
vben 已提交
39 40

export function useLocale() {
V
Vben 已提交
41
  const localeStore = useLocaleStoreWithOut();
42 43 44
  const getLocale = computed(() => localeStore.getLocale);
  const getShowLocalePicker = computed(() => localeStore.getShowPicker);

V
Vben 已提交
45 46
  const getAntdLocale = computed((): any => {
    return i18n.global.getLocaleMessage(unref(getLocale))?.antdLocale ?? {};
47
  });
V
vben 已提交
48 49 50

  // Switching the language will change the locale of useI18n
  // And submit to configuration modification
51 52 53
  async function changeLocale(locale: LocaleType) {
    const globalI18n = i18n.global;
    const currentLocale = unref(globalI18n.locale);
V
Vben 已提交
54 55 56
    if (currentLocale === locale) {
      return locale;
    }
V
vben 已提交
57

58 59 60 61 62 63
    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 已提交
64

65
    const { message, momentLocale, momentLocaleName } = langModule;
V
vben 已提交
66

67 68 69
    globalI18n.setLocaleMessage(locale, message);
    moment.updateLocale(momentLocaleName, momentLocale);
    loadLocalePool.push(locale);
V
vben 已提交
70

71 72
    setI18nLanguage(locale);
    return locale;
V
vben 已提交
73 74
  }

V
vben 已提交
75 76
  return {
    getLocale,
77
    getShowLocalePicker,
V
vben 已提交
78
    changeLocale,
79
    getAntdLocale,
V
vben 已提交
80 81
  };
}