vue-i18n和ElementUI國際化使用總結

vue-i18n官方文檔:http://kazupon.github.io/vue-i18n/en/started.html
element-ui文檔: http://element-cn.eleme.io/#/zh-CN/component/i18n
資料分享完了,現(xiàn)在開始總結vue-i18n使用方法:

  • 1、先看一下我的項目結構


    7MD}500FK{BG~NV2IC3J0@3.png
  • 2、廢話不多說,直接上代碼:

main.js

import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import i18n from './i18n/i18n';

Vue.use(ElementUI)

Vue.config.productionTip = false


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

i18n.js

import Vue from 'vue'
import locale from 'element-ui/lib/locale';
import VueI18n from 'vue-i18n'
import messages from './langs'
Vue.use(VueI18n)

//從localStorage中拿到用戶的語言選擇,如果沒有,那默認中文。
const i18n = new VueI18n({
    locale: localStorage.lang || 'cn',
    messages,
})
locale.i18n((key, value) => i18n.t(key, value)) //為了實現(xiàn)element插件的多語言切換

export default i18n

cn.js

import zhLocale from 'element-ui/lib/locale/lang/zh-CN'
const cn = {
    message: {
        'hello': '你好,世界',
        'msg': '提示',
    }  
}

export default cn;

en.js

    import enLocale from 'element-ui/lib/locale/lang/en'
    const en = {
        message: {
            'hello': 'hello, world',
            'msg': 'point out',
        }
    }

    export default en;

然后寫一個模板測試一下:

    <template>
      <div class="hello">
        <el-button type="primary" @click="switchChinese()">切換中文</el-button>
        <el-button type="primary" @click="switchEnlish()">切換英文</el-button>
        <p>{{$t('message.hello')}}</p> 
        <p>{{$t('message.msg')}}</p>
      </div>
    </template>

    <script>
    export default {
      name: 'HelloWorld',
      data () {
        return {
          msg: 'Welcome to Your Vue.js App'
        }
      },
      methods: {
        switchChinese(){
          this.$i18n.locale = 'cn'; 
        },
        switchEnlish(){
          this.$i18n.locale = 'en'; 
        }

      }
    }
    </script>

可能遇到的問題

1、記不住切換后的語言

我們在切換語言后,刷新一下瀏覽器又成了默認語言。那么可以在切換語言的方法中加入 localStorage.setItem("language", "你定義的語言包,如zh/en")

2、將this.$t() 寫到了data屬性里,切換語言不起作用

data是一次性生產(chǎn)的,你這么寫只能是在 data 初始化的時候拿到這些被國際化的值,并不能響應變化。
官方的解決辦法是,建議我們將表達式寫到 computed 屬性里,不要寫到 data 里

3、后臺獲取過來的動態(tài)數(shù)據(jù),在切換國際語言后不起作用

在witch中監(jiān)聽 i18n語言變化,重新調(diào)取接口。

watch: {
    '$i18n.locale'() {
        // 這里寫調(diào)用接口的邏輯
    }
}

好了,到這里就結束了,有時間還是多去看看vue-i18n文檔
最后聲明一下,這篇文章是借鑒下面這位老兄的文章寫的:https://segmentfault.com/a/1190000012779120#articleHeader1

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容