useLocale.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import {
  2. getLangJson
  3. } from '@/api/common';
  4. import {
  5. i18n
  6. } from './setupI18n';
  7. import messages from './index'
  8. export function useLocale() {
  9. function getBackLocale(locale) {
  10. const backLocale = locale || uni.getLocale()
  11. if (backLocale === 'zh-Hans') return 'zh-CN'
  12. if (backLocale === 'zh-Hant') return 'zh-TW'
  13. if (backLocale === 'en') return 'en-US'
  14. return backLocale
  15. }
  16. async function changeLocale(locale) {
  17. const defaultMessage = messages[locale] || {}
  18. const res = await getLangJson(getBackLocale(locale));
  19. if (!res || !res.data) return setLocale(locale, defaultMessage);
  20. const message = JSON.parse(res.data);
  21. setLocale(locale, {
  22. ...defaultMessage,
  23. ...message
  24. })
  25. return locale;
  26. }
  27. async function initLocale() {
  28. const locale = uni.getLocale()
  29. changeLocale(locale)
  30. }
  31. function setLocale(locale, message) {
  32. const globalI18n = i18n.global;
  33. globalI18n.setLocaleMessage(locale, message);
  34. globalI18n.locale = locale
  35. uni.setLocale(locale)
  36. }
  37. return {
  38. changeLocale,
  39. initLocale,
  40. setLocale,
  41. getBackLocale,
  42. };
  43. }