在src下创建目录lang,结构如下:
cn.js中:
export default {
// 页面共用
global:{
},
// home页面
home:{
title:'标题'
}
}
en.js:
export default {
// 页面共用
global:{
},
// home页面
home:{
title:'Title'
}
}
index.js;
import Vue from 'vue'
// 1.引入vue-i18n国际化组件
import VueI18n from 'vue-i18n'
// 2.引入elementUI自带的en/zh-CN语言包
import enLocale from 'element-ui/lib/locale/lang/en'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
// 3.引入本项目自定义的语言包
import rtodEnLocale from './en'
import rtodCnLocale from './cn'
// 4.引入elementUI本地化应用
import ElementLocale from 'element-ui/lib/locale'
// 5.创建语言包的json格式数据对象[包括:语言包对象]
const messages = {
en: {
...enLocale,
...rtodEnLocale
},
zh: {
...zhLocale,
...rtodCnLocale
}
}
Vue.use(VueI18n);
// 6.设置默认的本地语言为中文
const i18n = new VueI18n({
locale: 'zh', // 设置语言包中包含的语言类型
messages // 设置语言包对象
})
//重点:为了实现element插件的多语言切换
// 切换语言的方法:
// this.$i18n.locale='messages中的键:eg:en/zh'[在@click中不需要this]
ElementLocale.i18n((key, value) => i18n.t(key, value))
// 导出i18n语言包对象到Vue中注册用
export default i18n
main.js中:
import i18n from './lang'
export default new Vue({
i18n,
render: h => h(App)
}).$mount('#app')
组件中使用:
<template>
<div class="main">
{{$t('home.title')}}
</div>
</template>
切换语言:
<el-button @click="$i18n.locale='en'">切换为英文</el-button>