useI18n.ts 1.0 KB
Newer Older
V
vben 已提交
1
import { getI18n } from '/@/setup/i18n';
V
vben 已提交
2
import projectSetting from '/@/settings/projectSetting';
V
vben 已提交
3 4 5 6 7 8 9 10 11 12 13

export function useI18n(namespace?: string) {
  function getKey(key: string) {
    if (!namespace) {
      return key;
    }
    if (key.startsWith(namespace)) {
      return key;
    }
    return `${namespace}.${key}`;
  }
V
vben 已提交
14 15 16 17 18 19 20 21 22 23 24 25
  const normalFn = {
    t: (key: string) => {
      return getKey(key);
    },
  };

  if (!projectSetting.locale.show || !getI18n()) {
    return normalFn;
  }

  const { t, ...methods } = getI18n().global;

V
vben 已提交
26 27 28
  return {
    ...methods,
    t: (key: string, ...arg: Parameters<typeof t>) => {
V
vben 已提交
29
      if (!key) return '';
V
vben 已提交
30 31 32 33
      return t(getKey(key), ...arg);
    },
  };
}
V
vben 已提交
34 35 36 37 38 39 40

// Why write this function?
// Mainly to configure the vscode i18nn ally plugin. This function is only used for routing and menus. Please use useI18n for other places

// 为什么要编写此函数?
// 主要用于配合vscode i18nn ally插件。此功能仅用于路由和菜单。请在其他地方使用useIs18n
export const t = (key: string) => key;