useLocale.ts 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * Multi-language related operations
  3. */
  4. import type { LocaleType } from '/@/locales/types';
  5. import type { Ref } from 'vue';
  6. import { unref, ref } from 'vue';
  7. import { useLocaleSetting } from '/@/hooks/setting/useLocaleSetting';
  8. import { dateUtil } from '/@/utils/dateUtil';
  9. import { i18n } from './setupI18n';
  10. const antConfigLocaleRef = ref<any>(null);
  11. export function useLocale() {
  12. const { getLang, getLocale, setLocale: setLocalSetting } = useLocaleSetting();
  13. // Switching the language will change the locale of useI18n
  14. // And submit to configuration modification
  15. function changeLocale(lang: LocaleType): void {
  16. if (i18n.mode === 'legacy') {
  17. i18n.global.locale = lang;
  18. } else {
  19. ((i18n.global.locale as unknown) as Ref<string>).value = lang;
  20. }
  21. setLocalSetting({ lang });
  22. // i18n.global.setLocaleMessage(locale, messages);
  23. switch (lang) {
  24. // Simplified Chinese
  25. case 'zh_CN':
  26. import('ant-design-vue/es/locale/zh_CN').then((locale) => {
  27. antConfigLocaleRef.value = locale.default;
  28. });
  29. dateUtil.locale('cn');
  30. break;
  31. // English
  32. case 'en':
  33. import('ant-design-vue/es/locale/en_US').then((locale) => {
  34. antConfigLocaleRef.value = locale.default;
  35. });
  36. dateUtil.locale('en-us');
  37. break;
  38. // other
  39. default:
  40. break;
  41. }
  42. }
  43. // initialization
  44. function setLocale() {
  45. const lang = unref(getLang);
  46. lang && changeLocale(lang);
  47. }
  48. return {
  49. setLocale,
  50. getLocale,
  51. getLang,
  52. changeLocale,
  53. antConfigLocale: antConfigLocaleRef,
  54. };
  55. }