This article mainly introduces the implementation code of vue using vue-i18n to achieve internationalization. Now I will share it with you and give you a reference.
Requirements
Company projects need to be internationalized, click the button to switch Chinese/English
1. Installation
npm install vue-i18n --save
2. Inject into the vue instance and implement calling api and template syntax in the project
import VueI18n from 'vue-i18n' Vue.use(VueI18n) ; const i18n = new VueI18n({ locale: 'zh-CN', // 语言标识, 通过切换locale的值来实现语言切换,this.$i18n.locale messages: { 'zh-CN': require('./common/lang/zh'), // 中文语言包 'en-US': require('./common/lang/en') // 英文语言包 } }) new Vue({ el: '#app', i18n, // 最后 router, template: '', components: { App } })
3. Corresponding language package
zh. js Chinese language package:
export const lang = { homeOverview:'首页概览', firmOverview:'公司概述', firmReports:'财务报表', firmAppendix:'更多附录', firmIndex:'主要财务指标', firmAnalysis:'对比分析', firmNews:'新闻事件档案', firmOther:'其他功能', }
en.js English language package:
export const lang = { homeOverview:'Home overview', firmOverview:'firmOverview', firmReports:'firmReports', firmAppendix:'firmAppendix', firmIndex:'firmIndex', firmAnalysis:'firmAnalysis', firmNews:'firmNews', firmOther:'firmOther' }
4. Button control to switch language
this.$i18n.locale , when you assign the value to 'zh-CN', the navigation bar becomes Chinese; when the value is assigned to 'en-US', it becomes English:
中文
changeLangEvent() { console.log('changeLangEvent'); this.$confirm('确定切换语言吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { if ( this.$i18n.locale === 'zh-CN' ) { this.$i18n.locale = 'en-US';//关键语句 console.log('en-US') }else { this.$i18n.locale = 'zh-CN';//关键语句 console.log('zh-CN') } }).catch(() => { console.log('catch'); this.$message({ type: 'info', }); }); }
5. Template rendering
Static rendering:
{{$t('lang .homeOverview')}}
If it is element-ui, add a colon in front of what you want to translate
For example: label="user Name" will be changed to: label="$t('order.userName')"
Dynamic rendering:
{{navCompany}} computed:{ navCompany:function(){ if(this.nav_company){ let str = 'lang'+this.nav_company; return this.$t(str); } } },methods: { getTitle(title){ let str = 'lang.'+title; return this.$t(str); } } {{ getTitle(title1) }}
The above is what I compiled for everyone, I hope It will be helpful to everyone in the future.
Related articles:
JavaScript generates a time list within a specified range
nodejs method to implement file upload based on express
Detailed explanation of parameters based on webpack.config.js
The above is the detailed content of vue uses vue-i18n to implement internationalization code. For more information, please follow other related articles on the PHP Chinese website!