useLocale.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. interface LangModule {
  10. message: Recordable;
  11. momentLocale: Recordable;
  12. momentLocaleName: string;
  13. }
  14. const loadLocalePool: LocaleType[] = [];
  15. export function setLoadLocalePool(cb: (loadLocalePool: LocaleType[]) => void) {
  16. cb(loadLocalePool);
  17. }
  18. function setI18nLanguage(locale: LocaleType) {
  19. const localeStore = useLocaleStoreWithOut();
  20. if (i18n.mode === 'legacy') {
  21. i18n.global.locale = locale;
  22. } else {
  23. (i18n.global.locale as any).value = locale;
  24. }
  25. localeStore.setLocaleInfo({ locale });
  26. document.querySelector('html')?.setAttribute('lang', locale);
  27. }
  28. export function useLocale() {
  29. const localeStore = useLocaleStoreWithOut();
  30. const getLocale = computed(() => localeStore.getLocale);
  31. const getShowLocalePicker = computed(() => localeStore.getShowPicker);
  32. const getAntdLocale = computed((): any => {
  33. return i18n.global.getLocaleMessage(unref(getLocale))?.antdLocale ?? {};
  34. });
  35. // Switching the language will change the locale of useI18n
  36. // And submit to configuration modification
  37. async function changeLocale(locale: LocaleType) {
  38. const globalI18n = i18n.global;
  39. const currentLocale = unref(globalI18n.locale);
  40. if (currentLocale === locale) {
  41. return locale;
  42. }
  43. if (loadLocalePool.includes(locale)) {
  44. setI18nLanguage(locale);
  45. return locale;
  46. }
  47. const langModule = ((await import(`./lang/${locale}.ts`)) as any).default as LangModule;
  48. if (!langModule) return;
  49. const { message, momentLocale, momentLocaleName } = langModule;
  50. globalI18n.setLocaleMessage(locale, message);
  51. moment.updateLocale(momentLocaleName, momentLocale);
  52. loadLocalePool.push(locale);
  53. setI18nLanguage(locale);
  54. return locale;
  55. }
  56. return {
  57. getLocale,
  58. getShowLocalePicker,
  59. changeLocale,
  60. getAntdLocale,
  61. };
  62. }