i8n
i18n
i18n是internationalization这个单词的缩写,取了首字母i和结尾字母n,中间一用有18个字母,所以组合起来就所写成i18n,这是一个用于给vue国际化的插件, 它可以轻松地将一些本地化功能集成到你的 Vue.js 应用程序中
1、安装插件vue-i18n
npm i vue-i18n
//在 main.js 中导入并作为插件使用
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
2、创建语言包对象
// 1、创建中文语言包对象
const zh = {
username: '用户名',
email: '邮箱',
mobile: '手机'
}
// 2、创建英文语言包对象
const en = {
username: 'Username',
email: 'Email',
mobile: 'Mobile'
}
tip
两个第项中的键是一样的,后面在组件中要使用
3、组合对象
// 3、组合语言包对象
const messages = {
zh,
en
}
4、创建 i18n 实例
// 4、创建 VueI18n 实例,并为 messages 和 locale 属性赋值
const i18n = new VueI18n({
messages,
locale: 'en'
})
tip
- messages 属性要设置为第3步中组合的修啊ing
- locale:的值为 messages 对象中的某个 key 的值,如果设置为 en,则组件中使用 第1步中创建的 英文语言中包中的对应属性的值,如果设置为 zh,则使用 中文语言包中的属性的只
5、挂载对象
// 5、挂载 i18n
new Vue({
i18n,
render: h => h(App)
}).$mount('#app')
6、完整代码
import Vue from 'vue'
import App from './App.vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
// 1、创建中文语言包对象
const zh = {
username: '用户名',
email: '邮箱',
mobile: '手机'
}
// 2、创建英文语言包对象
const en = {
username: 'Username',
email: 'Email',
mobile: 'Mobile'
}
// 3、组合语言包对象
const messages = {
zh,
en
}
// 4、创建 VueI18n 实例,并为 messages 和 locale 属性赋值
const i18n = new VueI18n({
messages,
locale: 'en'
})
Vue.config.productionTip = false
// 5、挂载 i18n
new Vue({
i18n,
render: h => h(App)
}).$mount('#app')
7、组件中使用
<template>
<div id="app">
<p>{{ $t('username') }}</p>
<p>{{ $t('email') }}</p>
<p>{{ $t('mobile') }}</p>
</div>
</template>
扩展语言包对象
真实的项目中,可能很多地方都需要国际化,比如表格的表头、tab 栏、导航菜单等,我们可以 在语言包中创建多个键,分别存储这些模块的语言
// 1、创建中文语言包对象
const zh = {
table: {
username: '用户名',
email: '邮箱',
mobile: '手机'
},
menus: {
home: '首页',
download: '下载'
},
tabs: {
info: '商品描述',
comment: '评价'
}
}
// 2、创建英文语言包对象
const en = {
table: {
username: 'Username',
email: 'Email',
mobile: 'Mobile'
},
menus: {
home: 'Home',
download: 'DownLoad'
},
tabs: {
info: 'Describe',
comment: 'Comment On'
}
}
组件中使用
<template>
<div id="app">
<!-- 模拟表格中使用 -->
<div>
<p>{{ $t('table.username') }}</p>
<p>{{ $t('table.email') }}</p>
<p>{{ $t('table.mobile') }}</p>
</div>
<!-- 模拟导航菜单中使用 -->
<div>
<p>{{ $t('menus.home') }}</p>
<p>{{ $t('menus.download') }}</p>
</div>
<!-- 模拟tabs 选项卡中使用 -->
<div>
<p>{{ $t('tabs.info') }}</p>
<p>{{ $t('tabs.comment') }}</p>
</div>
</div>
</template>
更改里面 locale 的值,就会看到相应的变化
// 4、创建 VueI18n 实例,并为 messages 和 locale 属性赋值
const i18n = new VueI18n({
messages,
locale: 'zh'
})
在普通js中引用i18n $t 语法
//1.还是需要引入vue-i18n插件
import VueI18n from '@/i18n'
// 2.定义中英文语言包
const messages = {
en: {
message: {
connectionServerFailed: 'Connection to server failed'
}
},
zh: {
message: {
connectionServerFailed: '连接服务器失败'
}
}
}
// 3.实例化一个i18n对象
const i18n = new VueI18n({
locale: getLanguage(), // 语言标识
messages: messages // 上面自己定义的语 言包
})
//4.在需要使用多语言的地方调用即可。
error.message = i18n.tc('message.connectionServerFailed')
在vue文件script中引用语法
this.$t('layout.header-aside.tabs.close-left')