vue国际化配置及使用

vue项目国际化,目录结构如下:

其中i18n目录下文件为国际化内容

用于显示各种语言的文件在i18n/langs下,其中index.js为各种语言的整合文件,内容如下:

import en from './en'
import zh from './zh-cn'
import tw from './zh-tw'
import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
import twLocale from 'element-ui/lib/locale/lang/zh-TW'
import enLocale from 'element-ui/lib/locale/lang/en'

const message = {
  "en":Object.assign(en,enLocale),
  "zh":Object.assign(zh,zhLocale),
  "cht":Object.assign(tw,twLocale)
}
export default message;

zh-cn.js文件内容如下:

const cn = {
  message: {
    login:'登录',
  },
}
export default cn;

同时编写多语言插件的功能函数,在i18n/i18n.js写如下内容:

import Vue from 'vue'
import locale from 'element-ui/lib/locale'
import I18n from 'vue-i18n'
import messages from './langs/index'
import storageUtil from '../utils/storageUtil'
Vue.use(I18n)

const i18n = new I18n({
  locale: storageUtil.getLang(), // 其实就是en、zh、cht
  messages,
});
locale.i18n((key,value)=>{i18n.t(key,value)}) 
export default i18n;

上述内容准备好以后需要在main.js中进行配置,方式如下:

首先需要引入多语言切换功能函数

import i18n from './i18n/i18n'

然后在Vue中注册多语言功能,如下:

new Vue({
  el: '#app',
  components: { App },
  template: '<App/>',
  i18n
})

至此已经完成了多语言功能,如果想要切换语言时只要调用如下语句即可

this.$i18n.locale = "en"; // en、zh...

在静态模板中调用多语言字符串时使用的语句如下:

{{$t(`message.login`)}}

在js语句中使用多语言字符串时使用的语句如下:

this.$t('message.login')

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章