1.安装
npm install vue-i18n --save
2.在main.js中引用
import VueI18n from 'vue-i18n'
Vue.use(VueI18n) ;
new Vue({
el: '#app',
i18n,
router,
template: '<App/>',
components: { App }
})
3.新建语言包
zh.js中文语言包:
export const lang = {
home:"首页"
}
en.js 英文语言包:
export const lang = {
home:"Home"
}
4.切换语言事件
//中英文切换
changeLangEvent(val){
var _=this
console.log("_.val",val)
if (val == 2 ) {
_.$i18n.locale = 'en-US';//关键语句
console.log('en-US')
}else {
_.$i18n.locale = 'zh-CN';//关键语句
console.log('zh-CN')
}
},
5.使用
静态渲染:
<p>{{$t('lang.btnSoftware')}}</p>
如果是element-ui 的,在要翻译的前面加上冒号
比如:label="用户姓名" 就改成 :label="$t('order.userName')"
在data中使用:
this.messageOpen(_this.$t('lang.pleaseenter')+_this.$t('lang.Runpathimmediately'))
标注:在data中定义了_this.$t('lang.pleaseenter')后,切换语言后没有渲染切换后的数据,用computed解决
computed: {
rules:function () {
return (
{
name: [{
required: true,
/*message: `请填写软件名称`,*/
message: this.$t('lang.pleaseenter')+this.$t('lang.nameofsoftware'),
trigger: 'blur'
}],
}
)
}
},
注意:如果rules在computed中定义了,就不能在data中再定义,否则会报重复定义错误
|