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

67 lines
1.6 KiB
TypeScript
Raw Normal View History

2020-11-23 00:35:15 +08:00
/**
* Multi-language related operations
*/
import type { LocaleType } from '/@/locales/types';
2021-01-09 23:28:52 +08:00
import type { Ref } from 'vue';
2020-11-23 00:35:15 +08:00
import { unref, ref } from 'vue';
2020-11-23 23:24:13 +08:00
import { useLocaleSetting } from '/@/hooks/setting/useLocaleSetting';
2020-11-23 00:35:15 +08:00
2021-01-11 00:16:44 +08:00
import { dateUtil } from '/@/utils/dateUtil';
2020-11-23 00:35:15 +08:00
2021-01-09 23:28:52 +08:00
import { i18n } from './setupI18n';
2020-11-23 00:35:15 +08:00
const antConfigLocaleRef = ref<any>(null);
export function useLocale() {
2020-11-23 00:35:15 +08:00
const { getLang, getLocale, setLocale: setLocalSetting } = useLocaleSetting();
// Switching the language will change the locale of useI18n
// And submit to configuration modification
function changeLocale(lang: LocaleType): void {
2021-01-09 23:28:52 +08:00
if (i18n.mode === 'legacy') {
i18n.global.locale = lang;
} else {
((i18n.global.locale as unknown) as Ref<string>).value = lang;
}
2020-11-23 00:35:15 +08:00
setLocalSetting({ lang });
// i18n.global.setLocaleMessage(locale, messages);
switch (lang) {
// Simplified Chinese
case 'zh_CN':
import('ant-design-vue/es/locale/zh_CN').then((locale) => {
antConfigLocaleRef.value = locale.default;
});
2021-01-11 00:16:44 +08:00
dateUtil.locale('cn');
2020-11-23 00:35:15 +08:00
break;
// English
case 'en':
import('ant-design-vue/es/locale/en_US').then((locale) => {
antConfigLocaleRef.value = locale.default;
});
2021-01-11 00:16:44 +08:00
dateUtil.locale('en-us');
2020-11-23 00:35:15 +08:00
break;
// other
default:
break;
}
}
2020-11-23 00:35:15 +08:00
// initialization
2021-01-09 23:28:52 +08:00
function setLocale() {
2020-11-23 00:35:15 +08:00
const lang = unref(getLang);
lang && changeLocale(lang);
}
2020-11-23 00:35:15 +08:00
return {
2021-01-09 23:28:52 +08:00
setLocale,
2020-11-23 00:35:15 +08:00
getLocale,
getLang,
changeLocale,
antConfigLocale: antConfigLocaleRef,
};
}