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