需求 : 简单来说就是一键切换中英文两种状态
解决方式 :
1,安装 vue-i18n
npm install vue-i18n
2,将中英文js文件引入,在src下新建comment文件夹
如图:
3,在main.js 引入必要的资源
import VueI18n from 'vue-i18n'
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,
components: { App },
template: '<App/>'
})
4,在components组件的使用方式
例:
<a class="h-logo" @click="change()">{{$t('m.logout')}}</a>
<span><a href="">{{$t('m.1to2Years')}}</a></span>
<span><a href="">{{$t('m.abnormalCo')}}</a></span>
data() {
return {
lang: 'zh-CN'
}
},
methods: {
//切换语言
changeLangEvent() {
if (this.lang === 'zh-CN') {
this.lang = 'en-US';
this.$i18n.locale = this.lang;
} else {
this.lang = 'zh-CN';
this.$i18n.locale = this.lang;
}
},
data() {
return {
// options: [
// this.$t('text.volume_24H'), this.$t('text.market')
// ],
lang: 'zh-CN'
}
},
methods: {
//切换语言
changeLangEvent() {
if (this.lang === 'zh-CN') {
this.lang = 'en-US';
this.$i18n.locale = this.lang;
} else {
this.lang = 'zh-CN';
this.$i18n.locale = this.lang;
}
},
备注 : 也可以参考GitHub这个地址...