vue + elementUI 使用 i18n 实现国际化,及 i18n 的用法

1,519 阅读1分钟

main.js引用

import '@/utils/elementui'  //按需引入elementUI组件
import i18n from '@/lang/index' //引入i18n

new Vue({
  el: '#app',
  i18n,
  render: h => h(App)
})

lang/index.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'
import locale from 'element-ui/lib/locale'
import dictObj from './zh'
import Cookies from 'js-cookie'
import elementEnLocale from 'element-ui/lib/locale/lang/en'
import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'


Vue.use(VueI18n)

const messages = {
        'zh': {
            ...dictObj.zh,
            ...elementZhLocale
        },
        'en': {
            ...dictObj.en,
            ...elementEnLocale
        }
    }

const i18n = new VueI18n({
    locale: Cookies.get('lang') || 'zh',
    messages,
})
locale.i18n((key, value) => i18n.t(key, value))

export default i18n

因为我们的项目是中英文的,所以做了两种语言,前后端共用一份核心翻译文件,所以需要清洗核心文件为前端i18n所用。

核心文件如下:

let diction = {
  "version": "1.0.1",
  "lang_order": ["option_key", "zh", "en", "ru"],
  "dict": {
    "userRole": [
      ["超级管理员", "超级管理员", "Super administrator"],
      ["普通用户", "普通用户", "Common user"]
    ],
    "account": [
      ["用户名", "用户名", "Username"],
      ["用户密码", "用户密码", "Password"],
    ]
  }
}

为了使用方便,数组第一列为i18n key值,第二列为对应中文,第三列为对应英文,如果有多种语言,往后追加字符串即可。。。

清洗代码:

import ens from './dictionary/dictionary.json'

let { dict,lang_order } = ens
let dictObj = {}

for (let len in lang_order){
	let lang_ = {}
	if(len == 0) continue
	for(let key in dict){
		let data = {}
		dict[key].forEach(item =>{
			data[item[0]] = item[len]
		})
		lang_[key] = data
	}
	dictObj[lang_order[len]] = lang_
}

export default dictObj

使用$t

html模板
<div :title="$t('userRole.超级管理员')"

js模板
this.$t('userRole.超级管理员')