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