问题描述:
现在有一个大型的vue(“vue”: “^2.5.16”,)项目,引入了高版本的"vue-i18n": "^8.18.2"插件来实现国际化,同时项目中也用到了十几个ElementUI中的组件,现在,ElementUI中的组件国际化不兼容高版本的vue-i18n插件。
实际上要做什么操作:
项目用到的ElementUI组件有它自己的国际化语言包,项目中自己开发的组件也写了国际化语言包,要做的事就是把这两个资源包合在一起!
解决方案:
项目中按需引入了一部分ElementUI中的组件,比如(Button,Select,Input)
main.js
import Vue from 'vue'
import i18n from './util/locale/setLanguage'
import 'normalize.css/normalize.css'
import App from './App'
import router from './router'
import {
Button,
Select,
Input,
} from 'element-ui';
.name, Dialog);
Vue.component(Button.name, Button);
Vue.component(Select.name, Select);
Vue.component(Input.name, Input);
new Vue({
router,
i18n,
render: h => h(App)
}).$mount('#app')
setLanguage.js
import Vue from 'vue'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
import enLocale from './lang/en'
import zhLocale from './lang/zh-CN'
import zhTWLocale from './lang/zh-TW'
import ElementLocale from 'element-ui/lib/locale'
const i18n = new VueI18n({
locale: localStorage.getItem('locale') || 'zh_CN',
messages: {
zh_CN: zhLocale,
en_US: enLocale,
zh_TW: zhTWLocale,
},
})
ElementLocale.i18n((key, value) => i18n.t(key, value))
export default i18n
import ElementLocale from ‘element-ui/lib/locale’
这个index.js中的内容不贴了,自己去看吧。
en.js
import enLocale from 'element-ui/lib/locale/lang/en'
import deepmerge from 'deepmerge';
var enM = {
el: {
font:{
font1: 'Microsoft Yahei',
font2: 'Times New Roman',
font3: 'Bold',
font4: 'Italics',
font5: 'New Song Dynasty',
font6: 'Song-like',
},
common: {
quit: 'Quit',
cancel: 'Cancel',
confirm: 'Ok',
close: 'Close',
max: 'MaxiMize',
mix: 'minimize',
restore: 'Restore'
}
}
};
enM = deepmerge(enM, enLocale, { clone: true })
export default enM;
注意:
因为ElementUI的语言包最外层的对象名字是el,所以你自定义的语言文件对象名必须也是el,这样deepmerge才能把两个对象合并起来。合并之后名字是el,不会影响ElementUI组件里国际化的代码。
ElementUI的语言包en.js
ElementUI的语言包 和 自定义的语言包合并之后:
页面中的使用
{{ $t("el.common.confirm") }}
this.$t("el.common.quit")
import i18n from '@crm/locales'
i18n.t('el.common.Ok')
项目中引入了全部的ElementUI中的组件
setLanguage.js 文件中第五步改成如下:
import ElementUI from 'element-ui'
Vue.use(ElementUI,{
i18n:(key,value) =>i18n.t(key,value)
});
参考文章