vue——vue-i18n

vue 项目中如何实现国际化 vue-i18n

安装

npm install vue-i18n

引入

import VueI18n from 'vue-i18n'Vue.use(VueI18n) // 通过插件的形式挂载const i18n = new VueI18n({locale: 'zh',    // 语言标识//this.$i18n.locale // 通过切换 locale 的值来实现语言切换messages: { // js 方式'zh': require('@/plugins/lang/zh'),   // 中文语言包'en': require('@/plugins/lang/en')    // 英文语言包}//messages: { // json 方式//  'zh': require('@/plugins/lang/zh.json'),   // 中文语言包//  'en': require('@/plugins/lang/en.json')    // 英文语言包//}
})/* eslint-disable no-new */
new Vue({el: '#app',i18n,  // 不要忘记store,router,template: '',components: { App }
})

使用

语言包
  • en.js 英文语言包
// json
{"main": {"title": "me"}
}// js
export const main = {title: "me"
}
  • zh.js 中文语言包
//json
{"main": {"title": "我"}
}// js
export const main = {title: "我"
}

最后我们只需要通过触发事件的形式,来控制 locale 的值,去调用对应的语言包就可以实现国际化

组件中的一个点击事件进行切换
/*** 切换语言 */ changeLangEvent() {this.$confirm('确定切换语言吗?', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(() => {if ( this.lang === 'zh' ) {this.lang = 'en';this.$i18n.locale = this.lang; // 关键语句}else {this.lang = 'zh';this.$i18n.locale = this.lang; // 关键语句}}).catch(() => {this.$message({type: 'info',});          });
}
  • vue 中对于文字数据的渲染
<span v-text="$t('main.title')"></span>
<span>{{$t('main.title')}}</span>// js 获取
this.$t('main.title')


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部