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.

72 lines
1.8 KiB

  1. // 多组件库的国际化和本地项目国际化兼容
  2. import { App, WritableComputedRef } from "vue";
  3. import { storageLocal } from "/@/utils/storage";
  4. import { type I18n, createI18n } from "vue-i18n";
  5. // element-plus国际化
  6. import enLocale from "element-plus/lib/locale/lang/en";
  7. import zhLocale from "element-plus/lib/locale/lang/zh-cn";
  8. function siphonI18n(prefix = "zh-CN") {
  9. return Object.fromEntries(
  10. Object.entries(import.meta.globEager("../../locales/*.y(a)?ml")).map(
  11. ([key, value]) => {
  12. const matched = key.match(/([A-Za-z0-9-_]+)\./i)[1];
  13. return [matched, value.default];
  14. }
  15. )
  16. )[prefix];
  17. }
  18. export const localesConfigs = {
  19. zh: {
  20. ...siphonI18n("zh-CN"),
  21. ...zhLocale
  22. },
  23. en: {
  24. ...siphonI18n("en"),
  25. ...enLocale
  26. }
  27. };
  28. /**
  29. *
  30. * @param message message
  31. * @param isI18n true,,
  32. * @returns message
  33. */
  34. export function transformI18n(
  35. message: string | unknown | object = "",
  36. isI18n: boolean | unknown = false
  37. ) {
  38. if (!message) {
  39. return "";
  40. }
  41. // 处理存储动态路由的title,格式 {zh:"",en:""}
  42. if (typeof message === "object") {
  43. const locale: string | WritableComputedRef<string> | any =
  44. i18n.global.locale;
  45. return message[locale?.value];
  46. }
  47. if (isI18n) {
  48. return i18n.global.t.call(i18n.global.locale, message);
  49. } else {
  50. return message;
  51. }
  52. }
  53. // 此函数只是配合i18n Ally插件来进行国际化智能提示,并无实际意义(只对提示起作用),如果不需要国际化可删除
  54. export const $t = (key: string) => key;
  55. export const i18n: I18n = createI18n({
  56. legacy: false,
  57. locale: storageLocal.getItem("responsive-locale")?.locale ?? "zh",
  58. fallbackLocale: "en",
  59. messages: localesConfigs
  60. });
  61. export function useI18n(app: App) {
  62. app.use(i18n);
  63. }