index.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { isNull, forInObject, isEmpty, storage } from "@/cool";
  2. import { ref } from "vue";
  3. import { zhcn } from "./zh-cn";
  4. import { en } from "./en";
  5. import { es } from "./es";
  6. import { config } from "@/config";
  7. // 语言包对象,包含所有支持的语言
  8. const messages = {
  9. "zh-cn": zhcn,
  10. en,
  11. es
  12. };
  13. // 当前语言,默认中文
  14. export const locale = ref<string>("");
  15. // 设置当前语言
  16. export const setLocale = (value: string) => {
  17. locale.value = value;
  18. // #ifdef APP
  19. // APP 环境下,存储语言到本地
  20. storage.set("locale", value, 0);
  21. // #endif
  22. // #ifndef APP
  23. // 其他环境下,直接设置全局语言
  24. uni.setLocale(value);
  25. // #endif
  26. };
  27. // 获取当前语言
  28. export const getLocale = (): string => {
  29. let value: string;
  30. // #ifdef APP
  31. // APP 环境下,优先从本地存储获取
  32. const _locale = storage.get("locale") as string | null;
  33. if (_locale != null && !isEmpty(_locale)) {
  34. value = _locale;
  35. } else {
  36. // @ts-ignore
  37. value = uni.getDeviceInfo().osLanguage as string;
  38. }
  39. // #endif
  40. // #ifndef APP
  41. // 其他环境下,直接获取全局语言
  42. value = uni.getLocale();
  43. // #endif
  44. if (isNull(value) || isEmpty(value)) {
  45. value = config.locale;
  46. }
  47. return value;
  48. };
  49. // 不带参数的翻译方法
  50. export const t = (name: string) => {
  51. let data = messages[locale.value] as string[][] | null;
  52. if (data == null) {
  53. return name;
  54. }
  55. return data.find((e) => e[0] == name)?.[1] ?? name;
  56. };
  57. // 带参数的翻译方法
  58. export const $t = (name: string, data: any) => {
  59. let text = t(name);
  60. // 替换参数
  61. if (!isNull(data)) {
  62. forInObject(data, (value, key) => {
  63. if (typeof value === "number") {
  64. value = value.toString();
  65. }
  66. text = text.replaceAll(`{${key}}`, value as string);
  67. });
  68. }
  69. return text;
  70. };
  71. // 初始化语言设置
  72. export const initLocale = () => {
  73. locale.value = getLocale();
  74. // #ifndef APP
  75. // 监听语言切换事件,自动更新 locale
  76. uni.onLocaleChange((res) => {
  77. setLocale(res.locale!);
  78. });
  79. // #endif
  80. };