vue-vben-admin/src/locales/useLocale.ts

70 lines
1.8 KiB
TypeScript
Raw Normal View History

2020-11-23 00:35:15 +08:00
/**
* Multi-language related operations
*/
import type { LocaleType } from '/#/config';
2020-11-23 00:35:15 +08:00
2021-01-09 23:28:52 +08:00
import { i18n } from './setupI18n';
2021-04-10 19:25:49 +08:00
import { useLocaleStoreWithOut } from '/@/store/modules/locale';
2021-03-03 22:52:25 +08:00
import { unref, computed } from 'vue';
import { loadLocalePool, setHtmlPageLang } from './helper';
2020-11-23 00:35:15 +08:00
interface LangModule {
message: Recordable;
2021-11-10 22:12:10 +08:00
dateLocale: Recordable;
dateLocaleName: string;
}
function setI18nLanguage(locale: LocaleType) {
2021-04-10 19:25:49 +08:00
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() {
2021-04-10 19:25:49 +08:00
const localeStore = useLocaleStoreWithOut();
const getLocale = computed(() => localeStore.getLocale);
const getShowLocalePicker = computed(() => localeStore.getShowPicker);
2021-04-12 23:02:48 +08:00
const getAntdLocale = computed((): any => {
return i18n.global.getLocaleMessage(unref(getLocale))?.antdLocale ?? {};
});
2020-11-23 00:35:15 +08:00
// 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);
2021-04-10 19:25:49 +08:00
if (currentLocale === locale) {
return locale;
}
2020-11-23 00:35:15 +08:00
if (loadLocalePool.includes(locale)) {
setI18nLanguage(locale);
return locale;
}
const langModule = ((await import(`./lang/${locale}.ts`)) as any).default as LangModule;
if (!langModule) return;
2020-11-23 00:35:15 +08:00
2021-11-10 22:12:10 +08:00
const { message } = langModule;
2020-11-23 00:35:15 +08:00
globalI18n.setLocaleMessage(locale, message);
loadLocalePool.push(locale);
setI18nLanguage(locale);
return locale;
}
2020-11-23 00:35:15 +08:00
return {
getLocale,
getShowLocalePicker,
2020-11-23 00:35:15 +08:00
changeLocale,
getAntdLocale,
2020-11-23 00:35:15 +08:00
};
}