1.下载vue-i18n
npm install vue-i18n
2.引入i18n国际化插件
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
3.注册i18n实例并引入语言文件
const i18n = new VueI18n({
locale: 'chs', // 将要切换的语言,可以通过url拼的参数获取,用户行为select选择获取,本地manifest配置获取等,根据场景动态获取
messages: {
chs: require('@/assets/languages/zh.json'),
en: require('@/assets/languages/en.json')
}
})
4.将i18n注入到vue实例中
new Vue({
el: '#app',
router,
i18n,
components: { App},
template: '<App/>'
});
5.语言文件格式
// 中文
{
"common":{
"name":"名字",
"age":"年龄"
}
}
// 英文
{
"common":{
"name":"name",
"age":"age"
}
}
6.模板渲染
// 模板中
{{$t('common.name')}}
// js中
this.$t('common.name')
7.语言切换
this.$i18n.locale = 'en'