项目基于Vue+Typescript+iview,有国际化的需求,目前支持中文和英文两种语言。
自己国际化没有什么难度,可是typescript和iview仍是有点须要注意的,特此记录。html
Vue I18n 是 Vue.js 的国际化插件。它能够轻松地将一些本地化功能集成到你的 Vue.js 应用程序中。
基本的使用方法就很少介绍了,参考下列文档。后面介绍一些遇到的问题及解决办法。前端
参考文档:vue
<span>{{$t('m.common.name')}}</span>
调用$t
方法,参数传key
值。至于m.common.name
的key从何而来,咱们看一下i18n传入的的messages值。git
先看main.js
里,message传入两种语言的字符串对象。github
const messages = { 'zh-CN': require('../../static/locale/cn.js'), 'en-US': require('../../static/locale/en.js') } const i18n = new VueI18n({ locale: lang, messages })
其中zh-CN
的值:typescript
m = { common: { name: '名称' } }
en-US
的值:前端框架
m = { common: { name: 'Name' } }
到这里,明白了m.common.name
的key
怎么来的了吧!cookie
js代码中的使用方法是调用$i18n.t
方法app
data () { return { btnName: this.$i18n.t('m.common.create') } }
须要注意的是,与html中不一样,当i18n的locale切换时,html中用到的字符串会从新渲染,完成语言的切换,而js代码中的字符串没法实现。
网上有一个方案是将字符串获取放在computed中,或者是watch监听locale的变化,完成翻译的转换。
我这里,采用的是切换locale时,先将locale存在cookie中,而后刷新页面,完成国际化。框架
// 页面刷新 location.reload();
虽然这种办法存在问题(没法保持当前页面的状态),可是却能解决iview组件的国际化。
在ts代码中使用i18n的话,会报错:"TypeError: Cannot read property 't' of undefined"
因此须要将用到i18n的放在@Component中,以下:
@Component({ data () { return { btnName: this.$i18n.t('m.common.create') } } }) export default class ResourcePoolPage extends Vue { }
可是若是data中不是单纯的属性,而是复杂的对象,甚至会引用到methods中的方法时,你甚至须要把data和methods都挪至@Component里,那么就失去ts的优点了。下面的方法能够解决这个问题:
首先main.ts
里,改写,将Vue对象存在window。
window['vm'] = new Vue({ router, i18n, render: (h) => h(App), store: VuexStore }).$mount('#app')
在ts中须要用到时
export default class ResourcePoolPage extends Vue { btnName2: string = window['vm'].$i18n.t('m.common.create') }
若是嫌麻烦,能够封装一个翻译的方法,在ts里调用便可。
iview的国际化分为iview自身的国际化,以及iview接收到数据的国际化(如Table中的columns的国际化)。
在main.ts
里完成:
import iview from 'iview' import localeCN from 'iview/locale/zh-CN' import localeEn from 'iview/locale/en-US' const lang = VuexStore.getters.getLang // 获取当前的lang const locale = (lang === 'zh-CN') ? localeCN : localeEn Vue.use(iview, { locale })
数据的国际化没有特别的操做,依照前面的js和ts方法,只须要一个页面刷新操做便可。具体流程以下:
main.ts
初始会读cookie里的值,获取lang的设置,没有的话默认是中文。location.reload()
,刷新页面。