Vue-i18n is an international component of a project that can switch between multiple language versions. Many Vue projects use this plugin to handle language switching.
basic operation
1. Installation reference:
$ npm install vue-i18n
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-i18n/dist/vue-i18n.js"></script>
2. Introduce vue-i18n into main.js
import VueI18n from 'vue-i18n'
Vue.use(VueI18n) // 通过插件的形式挂载
const i18n = new VueI18n({
locale: 'zh-CN', // 语言标识
//this.$i18n.locale // 通过切换locale的值来实现语言切换
messages: {
'zh-CN': require('./common/lang/zh'), // 中文语言包
'en-US': require('./common/lang/en') // 英文语言包
}
})
/* eslint-disable no-new */
new Vue({
el: '#app',
i18n, // 记住要添加上
store,
router,
template: '<App/>',
components: {
App }
})
3. Make a js file, process en and zh modes, and then switch this.$i18n.locale
en.js English language pack:
export const m = { music: 'Music',//Netease Cloud Music findMusic: 'FIND MUSIC',//find music myMusic: 'MY MUSIC',//my music friend: 'FRIEND',//friend musician: 'MUSICIAN',//Musician download: 'DOWNLOAD'//Download client }
zh.js Chinese language pack:
export const m = { music: 'Netease Cloud Music', findMusic: 'discover music', myMusic: 'my music', friend: 'friend', musician: 'musician', download: 'download client' }
4. Language switching method
How to switch in a click event in my component.
changeLangEvent() {
this.$confirm('确定切换语言吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
if ( this.lang === 'zh-CN' ) {
this.lang = 'en-US';
this.$i18n.locale = this.lang;//关键语句
}else {
this.lang = 'zh-CN';
this.$i18n.locale = this.lang;//关键语句
}
}).catch(() => {
this.$message({
type: 'info',
});
});
}
The key point here is the ''key statement'': this.$i18n.locale, when you assign the value 'zh-CN', the navigation bar will become Chinese; when the value is 'en-US' , becomes English.
Scenario use
The use of the vue.js internationalization vue-i18n plug-in, the usage instructions in the template text, component method, js, and return method:
1. Use { {$t("xxx")}} in the text
{ {$t(“register.register”)}}
2. Use $t('xxx') in the component method
:title=“type===1 ? $t(‘selectDevice’) : $t(‘selectProduct’)”
3. Use in the js method: this.$i18n.t('xxx')
this.$i18n.t(‘register.imgCodeFirst’)')
this. i 18 n . t ( ′ d i s b a n d p ′ ) + ‘ i18n.t('disband_p')+` i18n.t(′disbandp′)+‘{ele.name} `+ this.$i18n.t(‘layer’)
4. In the method returned after the request
If it is used in the method returned after the request, you need to define a variable above, var this_ = this; and then use this_ inside to use it normally
Toast.info(this_.$i18n.t(‘register.getMsgCodeSucceed’));
5. How to write in the code in data()
label:this.$t(‘message.en’),
If the content is on an array or object, the official solution is to suggest that we write the expression into the computed attribute instead of data.