i18n
thl-ui 在 @thl-ui/core 中内置了一个小巧、无依赖的 i18n 引擎,并提供 English (en)、Tiếng Việt (vi)、日本語 (ja) 和 简体中文 (zh) 的内置文案。所有内置字符串(分页、表格、日期选择器、校验、上传、布局、菜单、页面模板…)均已翻译。
实时演示:切换语言
翻译
vue
<script setup lang="ts">
import { useI18n } from '@thl-ui/vue';
const { t, n, d, locale, setLocale } = useI18n();
</script>
<template>
<p>{{ t('pagination.total', { count: 3 }) }}</p>
<p>{{ n(1234.5, { style: 'currency', currency: 'USD' }) }} · {{ d(new Date()) }}</p>
<button @click="setLocale('ja')">日本語</button>
<!-- 或在任意位置使用 $t('common.save') -->
</template>tsx
import { useT, useLocale } from '@thl-ui/react';
const t = useT();
const [locale, setLocale] = useLocale();
<p>{t('pagination.total', { count: 3 })}</p>
<p>{t.n(1234.5, { style: 'currency', currency: 'USD' })} · {t.d(new Date())}</p>
<button onClick={() => setLocale('ja')}>日本語</button>ts
import { ThlI18nService, ThlTranslatePipe } from '@thl-ui/angular';
readonly i18n = inject(ThlI18nService);
// 模板:
// {{ 'pagination.total' | thlT: { count: 3 } }}
// {{ i18n.n(1234.5, { style: 'currency', currency: 'USD' }) }}
// <button (click)="i18n.setLocale('ja')">日本語</button>插值与复数
文案使用 {name} 占位符。复数形式是以 Intl.PluralRules 类别为 key 的对象(zero 可选,在 count === 0 时使用)。count 会按当前语言的数字格式进行格式化。
ts
pagination: {
showing: 'Showing {from} to {to} of {total} entries',
total: { one: '{count} item', other: '{count} items' },
}ts
t('pagination.total', { count: 1 }) // "1 item"
t('pagination.total', { count: 1200 }) // "1,200 items" (vi: "1.200 mục")添加 / 覆盖文案
在配置中传入 messages——它们会与内置文案深度合并:
ts
createThl({
locale: 'zh',
messages: {
vi: { common: { save: 'Lưu lại' }, app: { welcome: 'Xin chào, {name}!' } },
en: { app: { welcome: 'Welcome, {name}!' } },
},
});运行时:thl.i18n.mergeMessages('vi', { app: { bye: 'Tạm biệt' } })——组件会自动重新渲染。
添加新语言(懒加载)
ts
createThl({
locales: ['en', 'ja', 'vi', 'zh', 'ko'],
loadLocale: (l) => import(`./locales/${l}.ts`), // 返回 Messages 或 { default: Messages }
});
thl.setLocale('ko'); // 加载、合并,然后切换以 @thl-ui/locales/src/en.ts 为模板复制。ThlMessages 类型可帮助你检查是否完整:
ts
import type { ThlMessages } from '@thl-ui/locales';
const ko: ThlMessages = { /* TypeScript 会报告缺失的 key */ };从右到左(RTL)的语言(ar、he、fa、ur)会在 <html> 上设置 dir="rtl";样式使用逻辑属性,因此布局会自动镜像。
数字与日期格式化
n() 和 d() 封装了 Intl.NumberFormat / Intl.DateTimeFormat,使用映射后的 Intl locale(vi → vi-VN、ja → ja-JP、zh → zh-CN、en → en-US)。日期选择器、日历、表格和图表都使用同一个格式化器,因此切换语言会同时改变各处的月份名称、每周起始日和分隔符。
文案命名空间
| 命名空间 | 使用者 |
|---|---|
common.* | ok、cancel、save、search、loading、empty… |
pagination.*, table.* | Pagination、DataTable |
select.*, datepicker.*, upload.* | 表单控件 |
validation.* | rules.* 的错误信息 |
modal.*, toast.*, steps.*, session.* | 反馈类组件 |
layout.*, menu.* | AppLayout、Topbar、SettingsPanel、侧边菜单 |
pages.* | 页面模板(登录、收件箱、发票、价格、错误页…) |