提交 | 用户 | 时间
|
820397
|
1 |
import { i18n } from '@/plugins/vueI18n' |
H |
2 |
|
|
3 |
type I18nGlobalTranslation = { |
|
4 |
(key: string): string |
|
5 |
(key: string, locale: string): string |
|
6 |
(key: string, locale: string, list: unknown[]): string |
|
7 |
(key: string, locale: string, named: Record<string, unknown>): string |
|
8 |
(key: string, list: unknown[]): string |
|
9 |
(key: string, named: Record<string, unknown>): string |
|
10 |
} |
|
11 |
|
|
12 |
type I18nTranslationRestParameters = [string, any] |
|
13 |
|
|
14 |
const getKey = (namespace: string | undefined, key: string) => { |
|
15 |
if (!namespace) { |
|
16 |
return key |
|
17 |
} |
|
18 |
if (key.startsWith(namespace)) { |
|
19 |
return key |
|
20 |
} |
|
21 |
return `${namespace}.${key}` |
|
22 |
} |
|
23 |
|
|
24 |
export const useI18n = ( |
|
25 |
namespace?: string |
|
26 |
): { |
|
27 |
t: I18nGlobalTranslation |
|
28 |
} => { |
|
29 |
const normalFn = { |
|
30 |
t: (key: string) => { |
|
31 |
return getKey(namespace, key) |
|
32 |
} |
|
33 |
} |
|
34 |
|
|
35 |
if (!i18n) { |
|
36 |
return normalFn |
|
37 |
} |
|
38 |
|
|
39 |
const { t, ...methods } = i18n.global |
|
40 |
|
|
41 |
const tFn: I18nGlobalTranslation = (key: string, ...arg: any[]) => { |
|
42 |
if (!key) return '' |
|
43 |
if (!key.includes('.') && !namespace) return key |
|
44 |
//@ts-ignore |
|
45 |
return t(getKey(namespace, key), ...(arg as I18nTranslationRestParameters)) |
|
46 |
} |
|
47 |
return { |
|
48 |
...methods, |
|
49 |
t: tFn |
|
50 |
} |
|
51 |
} |
|
52 |
|
|
53 |
export const t = (key: string) => key |