useLocale.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /**
  2. * Multi-language related operations
  3. */
  4. import type { LocaleType } from '/#/config';
  5. import moment from 'moment';
  6. import { i18n } from './setupI18n';
  7. import { useLocaleStoreWithOut } from '/@/store/modules/locale';
  8. import { unref, computed } from 'vue';
  9. import { loadLocalePool, setHtmlPageLang } from './helper';
  10. interface LangModule {
  11. message: Recordable;
  12. momentLocale: Recordable;
  13. momentLocaleName: 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. return i18n.global.getLocaleMessage(unref(getLocale))?.antdLocale ?? {};
  31. });
  32. // Switching the language will change the locale of useI18n
  33. // And submit to configuration modification
  34. async function changeLocale(locale: LocaleType) {
  35. const globalI18n = i18n.global;
  36. const currentLocale = unref(globalI18n.locale);
  37. if (currentLocale === locale) {
  38. return locale;
  39. }
  40. if (loadLocalePool.includes(locale)) {
  41. setI18nLanguage(locale);
  42. return locale;
  43. }
  44. const langModule = ((await import(`./lang/${locale}.ts`)) as any).default as LangModule;
  45. if (!langModule) return;
  46. const { message, momentLocale, momentLocaleName } = langModule;
  47. globalI18n.setLocaleMessage(locale, message);
  48. moment.updateLocale(momentLocaleName, momentLocale);
  49. loadLocalePool.push(locale);
  50. setI18nLanguage(locale);
  51. return locale;
  52. }
  53. return {
  54. getLocale,
  55. getShowLocalePicker,
  56. changeLocale,
  57. getAntdLocale,
  58. };
  59. }