阅14
Vue3多语言国际化实现
安装vue-i18n
vue-i18n作为国际化插件,主要有两个版本8版本和9版本,其中9版本匹配的是vue3版本,推荐使用。 使用pnpm安装如下:
bashpnpm add vue-i18@11
全局注册
tsimport {createApp} from 'vue'; import {createI18n} from 'vue-i18n'; const i18n = createI18n({ // 设置i18n的配置 }); cosnt app = createApp({ // 创建app实例 }); // 注册中间件 app.use(i18n); app.mount('#app');
快速使用
创建i18n实例
tsconst i18n = createI18n({ locale:"ja", fallbackLocale:"en", // 转换目标语言失败时的回退 messages:{ en:{ message:{ hello:"hello,wolrd" } }, ja:{ message:{ hello:"こんにちは、世界" } }, } })
其中:
$t()是调用翻译的方法locale是需要本地化的语言fallbackLocale是需要回退的语言
模板代码
vue<template> <h1>{{$t('message.hello')}</h1> </template>
渲染结果
html<h1>こんにちは、世界</h1>
范围和区域设置更改
i18n对于语言的修改有两个范围,分别为本地范围和全局范围。

全局范围区域的更改
vue<div class="locale-changer"> <select v-model="$i18n.locale"> <option v-for="locale in $i18n.availableLocales" :key="`locale-${locale}`" :value="locale">{{ locale }}</option> </select> </div>
本地范围区域的更改
tsconst i18n = createI18n({ locale: 'ja', // set current locale // vue-i18n something options here ... // ... }) // create Vue app instance, install Vue I18n, and mount! createApp({ // something vue options here ... // ... }).use(i18n).mount('#app') // change locale via `global` property // when vue-i18n is being used with legacy: false, note that i18n.global.locale is a ref, so we must set it via .value: i18n.global.locale.value = 'en' // otherwise - when using legacy: true, we set it like this: i18n.global.locale = 'en'
消息的格式化
普通插值
vue-i18n 使用 {}进行占位插值。
- 设置
const messages = {
en: {
message: {
hello: '{msg} world'
}
}
}
- 使用
vue<p>{{ $t('message.hello', { msg: 'hello' }) }}</p>
列表插值
- 设置
tsconst messages = { en: { message: { hello: '{0} world' } } }
- 使用
vue<p>{{ $t('message.hello', ['hello']) }}</p>
文字插值
- 设置
tsconst messages = { en: { address: "{account}{'@'}{domain}" } }
- 使用
vue<p>email: {{ $t('address', { account: 'foo', domain: 'domain.com' }) }}</p>
ℹ️信息文字插值对于消息格式语法中的特殊字符(如 `{` 和 `}`)非常有用,这些字符不能直接在消息中使用。
链接的消息
如果要复用另一个消息的内容,可以使用链接的消息来实现。
- 设置
tsconst messages = { en: { message: { the_world: 'the world', dio: 'DIO:', linked: '@:message.dio @:message.the_world !!!!' } } }
- 使用
vue<p>{{ $t('message.linked') }}</p>
链接消息内置修饰符
以下修饰符是目前可用的内置修饰符。
upper: 将链接消息中的所有字符大写lower: 将链接消息中的所有字符小写capitalize: 将链接消息中的第一个字符大写
设置
tsconst messages = { en: { message: { homeAddress: 'Home address', missingHomeAddress: 'Please provide @.lower:message.homeAddress' } } }
使用
vue<label>{{ $t('message.homeAddress') }}</label> <p class="error">{{ $t('message.missingHomeAddress') }}</p>
特殊字符
{}@$|对于这些字符的处理需要使用文字插值,如:{'@'}。
自定义指令
不仅可以使用$t来进行翻译,对于一些简单文本还可以使用v-t的自定义指令来进行翻译。
字符串语法
- 设置
tsimport { createApp } from 'vue' import { createI18n } from 'vue-i18n' const i18n = createI18n({ locale: 'en', messages: { en: { hello: 'hi there!' }, ja: { hello: 'こんにちは!' } } }) const app = createApp({ data: () => ({ path: 'hello' }) }) app.use(i18n) app.mount('#app')
- 使用
vue<div id="string-syntax"> <!-- string literal --> <p v-t="'hello'"></p> <!-- keypath binding via data --> <p v-t="path"></p> </div>
对象语法
tsimport { createApp } from 'vue' import { createI18n } from 'vue-i18n' const i18n = createI18n({ locale: 'ja', messages: { en: { message: { hi: 'Hi, {name}!', bye: 'good bye!', apple: 'no apples | one apple | {count} apples' } }, ja: { message: { hi: 'こんにちは、 {name}!', bye: 'さようなら!', apple: 'リンゴはありません | 一つのりんご | {count} りんご' } } } }) const app = createApp({ data() { return { byePath: 'message.bye', appleCount: 7, } } }) app.use(i18n) app.mount('#object-syntax')
vue<div id="object-syntax"> <!-- literal --> <p v-t="{ path: 'message.hi', args: { name: 'kazupon' } }"></p> <!-- data binding via data --> <p v-t="{ path: byePath, locale: 'en' }"></p> <!-- pluralization --> <p v-t="{ path: 'message.apple', plural: appleCount }"></p> </div>
最小尺寸集
如果项目只使用基本的翻译功能,比如$t,则直接使用petite-vue-i18n插件就好,这个插件体积更小,性能和速度也更好。
复数形式
vue-i18n同时还支持复数的形式。
- 设置
tsconst messages = { en: { car: 'car | cars', apple: 'no apples | one apple | {count} apples' } }
- 使用
vue<p>{{ $t('car', 1) }}</p> <p>{{ $t('car', 2) }}</p> <p>{{ $t('apple', 0) }}</p> <p>{{ $t('apple', 1) }}</p> <p>{{ $t('apple', 10, { count: 10 }) }}</p>
格式化时间和日期
基本用法
- 设置
jsconst datetimeFormats = { 'en-US': { short: { year: 'numeric', month: 'short', day: 'numeric' }, long: { year: 'numeric', month: 'short', day: 'numeric', weekday: 'short', hour: 'numeric', minute: 'numeric' } }, 'ja-JP': { short: { year: 'numeric', month: 'short', day: 'numeric' }, long: { year: 'numeric', month: 'short', day: 'numeric', weekday: 'short', hour: 'numeric', minute: 'numeric', hour12: true } } } const i18n = createI18n({ datetimeFormats })
ts定义:
tsconst datetimeFormats: { [key: string]: { short: Intl.DateTimeFormatOptions; long: Intl.DateTimeFormatOptions; } } = { 'en': { short: { year: "numeric", month: 'short', day: 'numeric' }, long: { year: 'numeric', month: 'short', day: 'numeric', weekday: 'short', hour: 'numeric', minute: 'numeric' } }, 'zh-cn': { short: { year: 'numeric', month: 'short', day: 'numeric' }, long: { year: 'numeric', month: 'short', day: 'numeric', weekday: 'short', hour: 'numeric', minute: 'numeric', hour12: true } } };
- 使用
vue<p>{{ $d(new Date(), 'short') }}</p> <p>{{ $d(new Date(), 'long', 'ja-JP') }}</p>
格式化数字
- 设置
tsconst numberFormats = { 'en-US': { currency: { style: 'currency', currency: 'USD', notation: 'standard' }, decimal: { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 }, percent: { style: 'percent', useGrouping: false } }, 'ja-JP': { currency: { style: 'currency', currency: 'JPY', useGrouping: true, currencyDisplay: 'symbol' }, decimal: { style: 'decimal', minimumSignificantDigits: 3, maximumSignificantDigits: 5 }, percent: { style: 'percent', useGrouping: false } } } const i18n = createI18n({ numberFormats })
- 使用
vue<p>{{ $n(10000, 'currency') }}</p> <p>{{ $n(10000, 'currency', 'ja-JP') }}</p> <p>{{ $n(10000, 'currency', 'ja-JP', { useGrouping: false }) }}</p> <p>{{ $n(987654321, 'currency', { notation: 'compact' }) }}</p> <p>{{ $n(0.99123, 'percent') }}</p> <p>{{ $n(0.99123, 'percent', { minimumFractionDigits: 2 }) }}</p> <p>{{ $n(12.11612345, 'decimal') }}</p> <p>{{ $n(12145281111, 'decimal', 'ja-JP') }}</p>
加载中...