1.安装vue-i18n
npm i vue-i18n -S
2.设置语言的配置文件
在src下面创建locale文件夹,创建英文与中文的配置文件en.js与zh.js
// 这两个语言的资源文件根据项目的需求自行进行其中内容的配置
// src/locale/en.js
const message = {
message: {
hello: 'hello world'
},
footer: ['home', 'catgory', 'cart', 'users'],
userEdit: ['nickname', 'sex', 'birthday', 'tel', 'address', 'loginOut']
}
module.exports = message
// src/locale/zh.js
const messages = {
message: {
hello: '你好世界'
},
footer: ['首页', '分类', '购物车', '个人中心'],
userEdit: ['昵称', '性别', '出生日期', '电话', '地址管理', '退出登录']
}
module.exports = messages
// src/locale/index.js
// 在vue中使用i18n并生成他的实例,实例中根据语言地区的不同,去配置不同的地区信息
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
const i18n = new VueI18n({
locale: localStorage.getItem('lang') || 'en', // 设置地区
messages: {
en: require('./en'),
zh: require('./zh')
}// 设置地区信息
})
export default i18n
// 在vue中应用国际化的流程
// 在入口文件main.js中引用
import i18n from './locale'
new Vue({
i18n,
router,
store,
render: h => h(App)
}).$mount('#app')
// 这里举例locale配置信息的结构,下面列出使用的方式
{
"en": { // 'en' Locale
"key1": "this is message1", // 基本的
"nested": { // 嵌套
"message1": "this is nested message1"
},
"errors": [ // 数组
"this is 0 error code message",
{ // 数组嵌套对象
"internal1": "this is internal 1 error message"
},
[ // 数组嵌套数组
"this is nested array error 1"
]
]
},
"ja": { // 'ja' Locale
// ...
}
}
// 基于以上的locale配置,我们可以用以下的方式进行翻译
<!-- 基本的 -->
<p>{{ $t('key1') }}</p>
<!-- 嵌套 -->
<p>{{ $t('nested.message1') }}</p>
<!-- 数组 -->
<p>{{ $t('errors[0]') }}</p>
<!-- 数组嵌套对象 -->
<p>{{ $t('errors[1].internal1') }}</p>
<!-- 数组嵌套数组 -->
<p>{{ $t('errors[2][0]') }}</p>
// 在vue项目中,资源的正式使用方式为
// 1.在标签中使用,使用双大括号包裹
<p>{{ $t("message.hello") }}</p>
// 2.在属性中使用,使用绑定属性
<van-cell :title="$t('userEdit[5]')" />
// 3.js中使用,可以直接使用this
console.log(this.$t('userEdit[3]'))
// 在app中我们如何根据用户的选择来进行语言的切换呢?
// 我们可以根据用户的选择将语言环境存放在localstorage中,我们在创建i18n实例的时候可以通过localstorage去获取,同时也可以设置默认的语言具体可以查看上面的src/locale/index.js中的内容
<van-dropdown-menu>
<van-dropdown-item v-model="value1" :options="option1" @change="changeLang" />
</van-dropdown-menu>
// 切换语言
changeLang () {
localStorage.setItem('lang', this.value1)
}
效果图: