vben
2021-08-17 65735926d4cea2c72c2f1a30b60092b53afb9040
提交 | 用户 | age
737b1b 1 /**
V 2  * Multi-language related operations
3  */
f6cef1 4 import type { LocaleType } from '/#/config';
737b1b 5
5212ea 6 import moment from 'moment';
737b1b 7
99ac30 8 import { i18n } from './setupI18n';
215d8b 9 import { useLocaleStoreWithOut } from '/@/store/modules/locale';
9a1ba7 10 import { unref, computed } from 'vue';
d67772 11 import { loadLocalePool, setHtmlPageLang } from './helper';
6392b7 12
f6cef1 13 interface LangModule {
V 14   message: Recordable;
15   momentLocale: Recordable;
16   momentLocaleName: string;
ae3f83 17 }
18
f6cef1 19 function setI18nLanguage(locale: LocaleType) {
215d8b 20   const localeStore = useLocaleStoreWithOut();
V 21
f6cef1 22   if (i18n.mode === 'legacy') {
V 23     i18n.global.locale = locale;
24   } else {
25     (i18n.global.locale as any).value = locale;
26   }
27   localeStore.setLocaleInfo({ locale });
d67772 28   setHtmlPageLang(locale);
f6cef1 29 }
8882d4 30
V 31 export function useLocale() {
215d8b 32   const localeStore = useLocaleStoreWithOut();
f6cef1 33   const getLocale = computed(() => localeStore.getLocale);
V 34   const getShowLocalePicker = computed(() => localeStore.getShowPicker);
35
3c441a 36   const getAntdLocale = computed((): any => {
V 37     return i18n.global.getLocaleMessage(unref(getLocale))?.antdLocale ?? {};
f6cef1 38   });
737b1b 39
V 40   // Switching the language will change the locale of useI18n
41   // And submit to configuration modification
f6cef1 42   async function changeLocale(locale: LocaleType) {
V 43     const globalI18n = i18n.global;
44     const currentLocale = unref(globalI18n.locale);
215d8b 45     if (currentLocale === locale) {
V 46       return locale;
47     }
f6cef1 48
V 49     if (loadLocalePool.includes(locale)) {
50       setI18nLanguage(locale);
51       return locale;
99ac30 52     }
f6cef1 53     const langModule = ((await import(`./lang/${locale}.ts`)) as any).default as LangModule;
V 54     if (!langModule) return;
737b1b 55
f6cef1 56     const { message, momentLocale, momentLocaleName } = langModule;
737b1b 57
f6cef1 58     globalI18n.setLocaleMessage(locale, message);
5212ea 59     moment.updateLocale(momentLocaleName, momentLocale);
f6cef1 60     loadLocalePool.push(locale);
737b1b 61
f6cef1 62     setI18nLanguage(locale);
V 63     return locale;
8882d4 64   }
V 65
737b1b 66   return {
V 67     getLocale,
f6cef1 68     getShowLocalePicker,
737b1b 69     changeLocale,
f6cef1 70     getAntdLocale,
737b1b 71   };
V 72 }