推广小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
1.8 KiB

  1. import en from './en.json'//英语语言包
  2. import zhHans from './zh-Hans.json'//英语语言包
  3. import Vue from 'vue'
  4. import VueI18n from 'vue-i18n'
  5. // 国际化字段映射
  6. import objectLangMap from './objectLangMap'
  7. Vue.use(VueI18n)
  8. // 获取系统语言
  9. const systemInfo = uni.getSystemInfoSync();
  10. // const systemLang = 'en';
  11. const systemLang = systemInfo.language || 'en';
  12. console.log(systemInfo.language, systemLang);
  13. // 语言映射,将系统语言映射到我们支持的语言包
  14. const langMap = {
  15. 'zh': 'zh-Hans',
  16. 'zh_CN': 'zh-Hans',
  17. 'zh-Hans': 'zh-Hans',
  18. 'zh-Hant': 'zh-Hans', // 暂时都映射到简体中文
  19. 'zh-TW': 'zh-Hans',
  20. 'zh-HK': 'zh-Hans',
  21. 'en': 'en',
  22. 'en-US': 'en',
  23. 'en-GB': 'en'
  24. };
  25. // 获取语言:优先缓存 -> 系统语言 -> 默认英语
  26. const lang = uni.getStorageSync('language') || langMap[systemLang] || 'en';
  27. // const lang = 'en';
  28. // VueI18n构造函数所需要的配置
  29. const i18nConfig = {
  30. locale: lang,//当前语言
  31. // 所需要用的语言包
  32. messages:{
  33. en,
  34. 'zh-Hans' : zhHans,
  35. }
  36. }
  37. //将对象国际化
  38. Vue.prototype.$ot = (obj, type, key) => {
  39. // 如果对象不存在,返回空字符串
  40. if (!obj) return '';
  41. // 获取当前语言
  42. const currentLang = i18n.locale;
  43. // 获取字段映射配置
  44. const typeConfig = objectLangMap[type];
  45. if (!typeConfig) return obj[key] || '';
  46. const fieldConfig = typeConfig[key];
  47. if (!fieldConfig) return obj[key] || '';
  48. // 获取当前语言对应的字段名
  49. const fieldName = fieldConfig[currentLang];
  50. if (!fieldName) return obj[key] || '';
  51. // 返回对象中对应字段的值,如果不存在则返回默认字段的值
  52. return obj[fieldName] || obj[key] || '';
  53. }
  54. const i18n = new VueI18n(i18nConfig)
  55. export default i18n