2021-02-06 11:55:53 +02:00
|
|
|
export class I18n<T extends Record<string, any>> {
|
2022-01-28 04:39:49 +02:00
|
|
|
public ts: T;
|
2021-02-06 11:55:53 +02:00
|
|
|
|
|
|
|
constructor(locale: T) {
|
2022-01-28 04:39:49 +02:00
|
|
|
this.ts = locale;
|
2021-02-06 11:55:53 +02:00
|
|
|
|
|
|
|
//#region BIND
|
|
|
|
this.t = this.t.bind(this);
|
|
|
|
//#endregion
|
|
|
|
}
|
|
|
|
|
|
|
|
// string にしているのは、ドット区切りでのパス指定を許可するため
|
|
|
|
// なるべくこのメソッド使うよりもlocale直接参照の方がvueのキャッシュ効いてパフォーマンスが良いかも
|
2022-06-21 11:55:38 +03:00
|
|
|
public t(key: string, args?: Record<string, string | number>): string {
|
2021-02-06 11:55:53 +02:00
|
|
|
try {
|
2022-01-28 04:39:49 +02:00
|
|
|
let str = key.split('.').reduce((o, i) => o[i], this.ts) as unknown as string;
|
2021-02-06 11:55:53 +02:00
|
|
|
|
|
|
|
if (args) {
|
|
|
|
for (const [k, v] of Object.entries(args)) {
|
2022-06-21 11:55:38 +03:00
|
|
|
str = str.replace(`{${k}}`, v.toString());
|
2021-02-06 11:55:53 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return str;
|
2022-01-28 04:39:49 +02:00
|
|
|
} catch (err) {
|
2021-02-13 05:28:26 +02:00
|
|
|
console.warn(`missing localization '${key}'`);
|
2021-02-06 11:55:53 +02:00
|
|
|
return key;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|