1. 程式人生 > 實用技巧 >修改elementUI元件自帶的提示文字並支援國際化

修改elementUI元件自帶的提示文字並支援國際化

前言

  有時候我們開發的網站需要支援國際化,這個可以使用VueI18n來解決,但是遇到要求到每一個文字都必須按照她的意思走的領導,這種時候我們就不能用元件原先的文字了,而是要換成自定義的文字。

執行方式

  第一步:安裝專案依賴包

    cnpm install vue-i18n --save-dev

  第二步:在main.js中引入

// 配置語言
import ElementLocale from 'element-ui/lib/locale'
import VueI18n  from 'vue-i18n'
Vue.use(VueI18n)
const messages = {
  'zh_CN': require('../static/lang/chinese.json'),
  
'en_US': require('../static/lang/english.json'), } const i18n = new VueI18n({ locale: 'en_US', messages, silentTranslationWarn: true }) ElementLocale.i18n((key, value) => i18n.t(key, value));

  第三步:配置對應的中文或者英文的json/js檔案

  注意:這裡要把原先elementUI的文字也拿過來,如elementUI原本的英文語言配置:

 

    加入到我們的json檔案中:

  第四步:頁面中獲取

  

    $t就是直接獲取資料,$tc(‘SignIn-via’,2)是json檔案中的"SignIn-via":"Signinviamobilenumber|Signinviaemail",獲取Signinviaemail,下標是從1開始。

  第五步:寫中英文切換的方法(下面兩句程式碼直接放到方法裡即可)

this.$i18n.locale = e;
localStorage["lang"] = e;

  在App.vue的created()或mounted()裡面加上判斷,下次直接讀取快取即可

if (this.$i18n.messages[localStorage["lang"]]) this
.$i18n.locale = localStorage["lang"];

效果圖