vue-i18n
Recently, the vue project has encountered a need to globalize the project and require free switching between Chinese, English and Japanese. Here is a record of the use of the vue-i18n international language package processing plug-in. For details, please refer to: vue-i18n official documentation .
1. Installation
npm install vue-i18n --save
2. Configuration
Create a new i18n directory under the src directory, en.js English language pack, zh.js Chinese language pack, and ja.js Japanese language pack. The specific configuration is as follows:
zh.js
File (the specific configuration can be based on the actual situation, but the three file attribute values must correspond one to one)
module.exports = {
common: {
quanbu: '全部',
zanwushuju: '暂无数据',
qingxuanze: '请选择',
qingshuru: '请输入',
onlyNumber: '只能为数字',
onlyAddress: '请输入正确邮箱地址',
huoquzhong: '获取中...',
}
}
en.js
document
module.exports = {
common: {
quanbu: 'all',
zanwushuju: 'no data'
}
}
ja.js
document
module.exports = {
common: {
quanbu: '全部',
zanwushuju: '一時データなし',
qingxuanze: '選ぶ',
}
}
index.js
Files in the i18n directory
import Vue from 'vue'
import VueI18n from 'vue-i18n'
import locale from 'element-ui/lib/locale'
import zh from '@/common/lang/zh.js'
import en from '@/common/lang/en.js'
import ja from '@/common/lang/ja.js'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import enLocale from 'element-ui/lib/locale/lang/en'
import jaLocale from 'element-ui/lib/locale/lang/ja'
Vue.use(VueI18n)
const messages = {
zh: Object.assign(zh, zhLocale),
en: Object.assign(en, enLocale),
ja: Object.assign(ja, jaLocale),
}
//将vuei18n实例化,并传入配置信息
const i18n = new VueI18n({
locale: localStorage.getItem('locale') || 'zh', //当前语种,locale用来设置语种包
messages, //本地语言包
fallbackLocale: 'zh', //当前语种不存在时,默认设置当前语种为中文
numberFormats:{
//设置数字格式化
'en': {
currency: {
style: 'currency', currency: 'USD'
}
},
'zh': {
currency: {
style: 'currency', currency: 'JPY', currencyDisplay: 'symbol'
}
}
},
dateTimeFormats:{
//设置日期时间格式化
'en': {
short: {
//显示英文 年月日
year: 'numeric', month: 'short', day: 'numeric'
},
long: {
//显示英文 年月日 星期 小时 分钟
year: 'numeric', month: 'short', day: 'numeric',
weekday: 'short', hour: 'numeric', minute: 'numeric'
}
},
'zh': {
short: {
year: 'numeric', month: 'short', day: 'numeric'
},
long: {
year: 'numeric', month: 'short', day: 'numeric',
weekday: 'short', hour: 'numeric', minute: 'numeric'
}
}
}
})
locale.i18n((key, value) => i18n.t(key, value)) //为了实现element插件的多语言切换
export default i18n
The main entry file main.js is introduced
import Vue from 'vue'
import App from '@/common/App.vue'
import router from '@/router'
import store from '@/store'
import i18n from '@/i18n'
new Vue({
router,
store,
i18n,
render: h => h(App),
}).$mount('#app')
Switch between Chinese, English and Japanese languages
window.localStorage.removeItem('locale')
window.localStorage.setItem('locale', 'en') //'zh' 'ja'
window.location.reload() //刷新当前页面,可能会从缓存中读取页面
3. i18n usage
- Use of $t (formatting)
Simple to use:
//template 需要使用 {
{}} 将 name包装起来
<div>{
{
$t('common.quanbu')}}</div> //数据配置见zh.js文件
// js
this.$t('common.quanbu')//组件中使用
Naming format:
const messages = {
en: {
common: {
title: '全部, {name}'
}
}
}
<p>{
{
$t('common.title', {
name: '动物' }) }}</p> //输出:-->全部动物
//再例如:
const messages = {
en: {
common: {
title: '{name1},{name2}你好'}
}
}
<p>{
{
$t('common.title', {
name1: '张三',name1: '李四' }) }}</p> //输出:-->张三,李四你好
> Note: When using dynamic variables in i18n, the second parameter of $t is an object, and all variables that need to be dynamically added in the message are in the second parameter.
- Use of $tc (plural)
const messages = {
en: {
apple: 'no apples | one apple | {count} apples',
banana: 'no bananas | {n} banana | {n} bananas'
}
}
//在组件内使用
<p>{
{
$tc('apple', 2, {
count: 10 }) }}</p> //-->10 apples
<p>{
{
$tc('apple', 2) }}</p> // -->2 apples
<p>{
{
$tc('apple', 10, {
count: 10 }) }}</p> //-->10 apples
<p>{
{
$tc('apple', 100) }}</p> // -->10 apples
<p>{
{
$tc('banana', 1, {
n: 1 }) }}</p> // -->1 banana
<p>{
{
$tc('banana', 1) }}</p> // -->1 banana
<p>{
{
$tc('banana', 100, {
n: 'too many' }) }}</p> // ->>too many bananas
1. When defining plural numbers, they must be separated by the | pipe character. When using the pipe delimiter, you must use
$tc
2. When the | pipe character is equal to 1, the index starts from 1, and the maximum index is 2; when the pipe character is greater than 1, the index starts from 0 (similar to an array), and the maximum index is the pipe character. Number
3. Get the corresponding language text by using $tc ("plural", index)
- dateTimeFormats date time formatting
$d
//日期时间格式化配置
dateTimeFormats:{
'en': {
short: {
//显示英文 年月日
year: 'numeric', month: 'short', day: 'numeric'
},
long: {
//显示英文 年月日 星期 小时 分钟
year: 'numeric', month: 'short', day: 'numeric',
weekday: 'short', hour: 'numeric', minute: 'numeric'
}
},
'zh': {
short: {
year: 'numeric', month: 'short', day: 'numeric'
},
long: {
year: 'numeric', month: 'short', day: 'numeric',
weekday: 'short', hour: 'numeric', minute: 'numeric'
}
}
}
$d
usage of
//在组件中使用
<p>{
{
$d(new Date(), 'short') }}</p>
<p>{
{
$d(new Date(), 'long') }}</p>
<p>{
{
$d(new Date(), 'short','zh') }}</p>
<p>{
{
$d(new Date(), 'long', 'zh') }}</p>
//输出
Jul 31, 2022
Sat, Jul 31, 2022, 5:55 PM
2022年07月23日
2018年07月23日 周六 下午5:55
- numberFormatsnumber formatting
$n
//数字格式化配置
numberFormats:{
'en': {
currency: {
style: 'currency', currency: 'USD'
}
},
'zh': {
currency: {
style: 'currency', currency: 'JPY', currencyDisplay: 'symbol'
}
}
},
$n
usage of
<p>{
{
$n(100, 'currency') }}</p> //-->$100.00
<p>{
{
$n(100, 'currency', 'zh') }}</p> //-->¥100
Three parameters:
- @param number passes in the number
- Formatting scheme called by @param path
- @param locale language used, default current this.$i18n.locale
4. Commonly used methods
this.i18n.getLocaleMessage('en')//获取全局某个语言的语言包,返回是一个对象
this.$i18n.mergeLocaleMessage('zh', local.zh)//向全局中文语言包中补充内容
5. vt use
//locale='en'
const messages = {
en: {
message: {
title: hello'}
},
zh:{
message: {
title: '哈哈{name}'}
}
}
//组件中使用1 字符串用法
<p v-t="'message.title'"></p> //--> hello
//组件中使用2 对象用法
<p v-t="{ path: 'message.title', locale: 'zh', args: { name: 'wo' } }"></p> //-->哈哈wo
v-t
See $t
the link for comparison: The difference between $t and vt .
-
1.
- Advantages: You can flexibly use mustash syntax { {}} in templates, and you can also flexibly use calculation props and methods in Vue instances.
- Missing: It is executed every time it is re-rendered, so it consumes more performance. 2.
- Advantage: When translated once, it has better performance than the $t method because it uses custom directives for caching.
-
Cons:
v-t
Not flexible to use$t
as it is quite complex. The translated contentv-t
will be inserted intotextContent
the element.
$t
It is an extended Vue instance method
v-t
It is a custom instruction
6. Component interpolation
For details on component interpolation usage, see the link: Basic Usage and Advanced Usage .
//高级用法
<i18n path="info" tag="p">
//limit、action控制插入位置,通过place来指定出现在html中的位置
<span place="limit">{
{
changeLimit }}</span>
<a place="action" :href="changeUrl">{
{
$t('change') }}</a>
</i18n>
const messages = {
en: {
info: 'You can {action} until {limit} minutes from departure.',
change: 'change your flight',
refund: 'refund the ticket'
}
}
const i18n = new VueI18n({
locale: 'en',
messages
})
new Vue({
i18n,
data: {
changeUrl: '/change',
refundUrl: '/refund',
changeLimit: 15,
refundLimit: 30
}
}).$mount('#app')
// result
<p>
You can <a href="/change">change your flight</a> until <span>15</span> minutes from departure.
</p>