useLocale.ts 1.9 KB

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