在 Vue.js 中使用 Vue I18n 插件进行国际化(i18n)时,$t
方法通常用于在模板或组件中翻译文本。$t
方法可以接受多个参数,但最常用的有两个:
- 消息键(message key):这是必需的参数,表示要翻译的文本的键名。
- 参数对象(optional parameters):这是一个可选参数,用于在翻译文本中插入动态数据。
基本用法($t)
1. 只有一个消息键
<template>
<p>{{ $t('hello') }}</p>
</template>
假设你的翻译文件中有以下内容:
{ "hello": "Hello, world!" }
这将渲染为:Hello, world!
2. 消息键和参数对象
如果你的翻译文本包含动态部分,你可以使用参数对象来传递这些动态值。
<template>
<p>{{ $t('welcome', { name: 'John' }) }}</p>
</template>
假设你的翻译文件中有以下内容:
{ "welcome": "Welcome, {name}!" }
这将渲染为:Welcome, John!
参数对象的详细用法($t)
参数对象可以包含多个键值对,每个键值对都会替换翻译文本中相应的占位符。
<template>
<p>{{ $t('greeting', { name: 'John', count: 3 }) }}</p>
</template>
假设你的翻译文件中有以下内容:
{ "greeting": "Hello {name}, you have {count} new messages." }
这将渲染为:Hello John, you have 3 new messages.
复数形式($tc)
某些语言有复数形式,Vue I18n 也支持这种用法,不过这是通过特殊的语法处理的,而不是简单地传递更多参数。
<template>
<p>{{ $tc('apple', 1, { count: 1 }) }}</p>
<p>{{ $tc('apple', 5, { count: 5 }) }}</p>
</template>
假设你的翻译文件中有以下内容:
{ "apple": "You have {count} apple | You have {count} apples" }
这将分别渲染为:You have 1 apple. You have 5 apples.
判断该翻译是否存在($te)
<template>
<p>{{ $te('hello') }}</p>
</template>
假设你的翻译文件中有以下内容:
{ "hello": "Hello, world!" }
这将分别渲染为:true
展示当前日期($d)
<template>
<p>{{ $d(new Date) }}</p>
<!-- <p>{{ $d(new Date, options) }}</p> -->
</template>
这将分别渲染为:2024/12/30
格式化数字,如货币、百分比等($n)
<template>
<p>{{ $n(1234567.89) }}</p>
<!-- <p>{{ $n(1234567.89, options ) }}</p> -->
</template>
这将分别渲染为:1,234,567.89
第二个参数可以传入跟多的配置参数
options = {
style: 'decimal' | 'currency' | 'percent', // “十进制”|“货币”|“百分比”
currency: string, // ISO 4217 currency codes // 货币:字符串,ISO 4217货币代码
currencyDisplay: 'symbol' | 'code' | 'name', // '符号'|'代码'|'名称'
useGrouping: boolean, // 分组
minimumIntegerDigits: number, // 最小整数位数
minimumFractionDigits: number, // 最小分数位数
maximumFractionDigits: number, // 最大分数位数
minimumSignificantDigits: number, // 最小有效数字
maximumSignificantDigits: number, // 最大有效数字
localeMatcher: 'lookup' | 'best fit', // “查找”|“最佳匹配”
formatMatcher: 'basic' | 'best fit' // “基本”|“最适合”
}
总结
- $t 方法:接受至少一个参数(消息键),和一个可选的参数对象用于动态替换文本中的占位符。
- $tc 方法:用于处理复数形式的翻译。
- $te 方法:用于判断该翻译是否存在。
- $d 方法:用于处理时间格式的展示。
- $n 方法: 用于对数字的转换成货币或者百分比使用。
通过灵活使用这些方法,你可以轻松地在 Vue.js 应用中实现国际化。