Vue国际化的使用
首先是是在main.js文件中把国际化引入进来
main.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import Vue from 'vue'
import App from './App'
import router from './router'
import VueI18n from 'vue-i18n'
Vue.use(VueI18n)
Vue.config.productionTip = false
const i18n = new VueI18n({
locale: 'zh-CN',
messages: {
'zh-CN': {
'detail1': '详情1',
'detail2': '详情2',
'detail3': '详情3',
'year': '年'
},
'en-US': {
'detail1': 'Detail1',
'detail2': 'Detail2',
'detail3': 'Detail3',
'year': 'year'
}
}
})
new Vue({
el: '#app',
i18n: i18n,
router,
components: { App },
template: '<App/>'
}) |
其中我现在先在这个文件里面简单配置一些国际化的数据,放到常量i18n中,其中locale就是用来配置当前系统的语言的。目前这里采用的中文的,如果页面可以支持多种语言切换的话,这事件触发后就是改这里的配置的值,若改成英文,这设置为“en-US”
接下来就是在页面中使用的问题了。
第一种使用方式:在视图模板中直接使用,采用{{$t('xxxx')}}的方式。如下我现在使用'detail1'这个的国际化:
页面显示的效果就是:
中文效果:
英文效果:
第二种使用方式,是在脚本里面使用,这时可以采用 this.$t('xxxx')的方式。如下
test.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <template> <div> <h1>{{$t('detail1')}}</h1> <el-button @click="print">打印</el-button> </div> </template> <script> export default{ methods:{ print(){ console.log(this.$t('detail1')) } }, } </script> <style> </style> |
因为第二种方式中的this,指的是vue实例,所以这种方式在.vue结尾的的文件中能够生效。但是如果是例如在我们定义常量的文件里面要使用的话,就行不通了。那我们在常量中定义的数据,到页面显示,要怎样才能也使用上这个国际化呢。这个我们就来看下第三种方式。
第三种使用方式,在普通js文件中中配置,在页面上也展示国际化。
首先我们现在main.js文件中的国际化里面增加月份的国际化配置:
main.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | const i18n = new VueI18n({ locale: 'zh-CN', messages: { 'zh-CN': { 'detail1': '详情1', 'detail2': '详情2', 'detail3': '详情3', 'year': '年', 'month1': '1月', 'month2': '2月', 'month3': '3月' }, 'en-US': { 'detail1': 'Detail1', 'detail2': 'Detail2', 'detail3': 'Detail3', 'year': 'year', 'month1': 'January', 'month2': 'February', 'month3': 'March' } } }) |
然后我们准备一个constant.js文件。在里面如下配置:
constants.js
1 2 3 | export const months = ['month1', 'month2', 'month3'].map((item, index) => { return {'label': item, 'value': index + 1} }) |
这里注意的是,我这里的月份,直接使用的就是我们国际化里面配置的月份的key值。接下来我们就来页面上使用了。
这里把月份放到下拉框里面展示为例:
test.vue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | <template> <div> <h1>{{$t('detail1')}}</h1> <el-button @click="print">打印</el-button> <el-select v-model="month" placeholder="请选择月份"> <el-option v-for="item in months" :key="item.value" :label="$t(item.label)" :value="item.value"> </el-option> </el-select> </div> </template> <script> import {months} from '@/util/constants' export default{ data(){ return{ month:'', months:[] } }, methods:{ print(){ console.log(this.$t('detail1')) } }, created(){ this.months = months } } </script> <style> </style> |
这里注意的一点就是,在视图模型中,下拉框的label采用 :label="$t(item.label)"的方式,从而来到达国际展示的方式。
中文页面效果如下:
英文页面效果如下:
到此,三种方式介绍完毕。因为在开发中遇到这样的问题,故顺便总结下分享出来。如果大家有其他类似的问题或方式可以留言分享^_^。
作者:绝对小孩儿
链接:https://www.cnblogs.com/absolute-child/p/9425968.html