/***
* 国际化实现!!!
* huaicheng151201@163.com
* 2020年11月1日
*
* 参数说明
* options:
* - locale: 初始化语言
* - messages: 语言配置项
*
* 例如:
{
locale: "zh_CN",
messages: {
"zh_CN": {
option: {
test: "测试"
}
}
}
}
*/
export default {
install: (app, options) => {
app.mixin({
data(){
return {
v_locale: options.locale,
v_message: options.messages
}
},
methods: {
setV18nLang(lang){
this.v_locale = lang
},
$v(str){
try{
//return eval(`this.v_message.${this.v_locale}.${str}`)
//下面方式比evel安全
const units = str.split(".")
let result = this.v_message[this.v_locale]
for(let v of units){
if(result[v]) result = result[v]
else throw ''
}
return result;
}catch(e){
return str
}
},
setVi8nMessageLocale(object = {}){
Object.assign(this.v_message, object)
}
}
})
}
}
在vue3中:
import vi8n from 'v18n';
const messages = {
"zh_CN": {
option: {
test: "测试"
}
}
}
createApp(App)
.use(vi8n, {
locale: "zh_CN",
messages: messages
})
.mount('#app')
//在组件中
<div>{{$v("option.realUser")}}</div>
//切换语言
this.setV18nLang('en_US');
//增加语言配置
this.setVi8nMessageLocale({
en_US: {
option: { realUser: 'real' }
}
})