useLocale.ts 1.8 KB

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