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')

 

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