useI18n.ts 982 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. import { getI18n } from '/@/setup/i18n';
  2. export function useI18n(namespace?: string) {
  3. function getKey(key: string) {
  4. if (!namespace) {
  5. return key;
  6. }
  7. if (key.startsWith(namespace)) {
  8. return key;
  9. }
  10. return `${namespace}.${key}`;
  11. }
  12. const normalFn = {
  13. t: (key: string) => {
  14. return getKey(key);
  15. },
  16. };
  17. if (!getI18n()) {
  18. return normalFn;
  19. }
  20. const { t, ...methods } = getI18n().global;
  21. return {
  22. ...methods,
  23. t: (key: string, ...arg: any): string => {
  24. if (!key) return '';
  25. return t(getKey(key), ...(arg as Parameters<typeof t>));
  26. },
  27. };
  28. }
  29. // Why write this function?
  30. // Mainly to configure the vscode i18nn ally plugin. This function is only used for routing and menus. Please use useI18n for other places
  31. // 为什么要编写此函数?
  32. // 主要用于配合vscode i18nn ally插件。此功能仅用于路由和菜单。请在其他地方使用useI18n
  33. export const t = (key: string) => key;