useLocale.ts 1.6 KB

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