index.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import { isNull, forInObject, storage } from "../utils";
  2. import { ref } from "vue";
  3. // 解析语言包
  4. function parse(val: string[][]) {
  5. const isCustom = val.length == 1 && val[0].length == 1;
  6. if (!isCustom) {
  7. return val;
  8. }
  9. return val[0][0].split("<__&__>").map((e) => e.split("<__=__>"));
  10. }
  11. // 语言包映射对象
  12. const messages = {};
  13. // 当前语言
  14. export const locale = ref<string>("");
  15. // 默认语言
  16. export const defaultLocale = ref<string>("none");
  17. // 设置当前语言
  18. export const setLocale = (value: string) => {
  19. locale.value = value;
  20. // 设置缓存
  21. storage.set("locale", value, 0);
  22. };
  23. // 获取当前语言
  24. export const getLocale = (): string => {
  25. let value = storage.get("locale") as string;
  26. if (value == "") {
  27. if (defaultLocale.value != "none") {
  28. value = defaultLocale.value;
  29. } else {
  30. // #ifdef APP
  31. // @ts-ignore
  32. value = uni.getDeviceInfo().osLanguage as string;
  33. // #endif
  34. // #ifndef APP
  35. value = uni.getLocale();
  36. // #endif
  37. }
  38. }
  39. return value;
  40. };
  41. // 追加数据
  42. export const appendLocale = (name: string, data: string[][]) => {
  43. if (messages[name] == null) {
  44. messages[name] = [] as string[][];
  45. }
  46. (messages[name] as string[][]).unshift(...parse(data));
  47. };
  48. // 不带参数的翻译方法
  49. export const t = (name: string) => {
  50. let data = messages[locale.value] as string[][] | null;
  51. if (data == null) {
  52. return name;
  53. }
  54. let text = data.find((e) => e[0] == name)?.[1];
  55. if (text == null || text == "") {
  56. text = name;
  57. }
  58. return text;
  59. };
  60. // 带参数的翻译方法
  61. export const $t = (name: string, data: any) => {
  62. let text = t(name);
  63. // 替换参数
  64. if (!isNull(data)) {
  65. forInObject(data, (value, key) => {
  66. if (typeof value === "number") {
  67. value = value.toString();
  68. }
  69. text = text.replaceAll(`{${key}}`, value as string);
  70. });
  71. }
  72. return text;
  73. };
  74. // 初始化语言设置
  75. export function initLocale(value: string) {
  76. // 设置默认语言
  77. defaultLocale.value = value;
  78. // 设置当前语言
  79. locale.value = getLocale();
  80. // #ifndef APP
  81. // 监听语言切换事件,自动更新 locale
  82. uni.onLocaleChange((res) => {
  83. setLocale(res.locale!);
  84. });
  85. // #endif
  86. }