1. 程式人生 > >vue用i18n實現多語言支援(國際化)

vue用i18n實現多語言支援(國際化)

vue-i18n是用於多語言適配的vue外掛,主要用於前端專案的國際化應用。

個簡單的例子:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>getting started</title>
    <script src="../../node_modules/vue/dist/vue.min.js"></script>
    <script src="../../dist/vue-i18n.min.js"></script>
  </head>
  <body>
    <div id="app">
      <p>{{ $t("message.hello") }}</p>
    </div>
    <script>
      var messages = {
        en: {
          message: {
            hello: 'hello world'
          }
        },
        ja: {
          message: {
            hello: 'こんにちは、世界'
          }
        }
      }
      
      Vue.use(VueI18n)

      var i18n = new VueI18n({
        locale: 'ja',
        messages: messages
      })
      new Vue({ i18n: i18n }).$mount('#app')
    </script>
  </body>
</html>

我們可以看到vue-i18n的使用非常的簡單,我們只需要定義好對應的語言包messages,然後設定一個預設語言型別locale,然後例項化出一個i18n物件並傳入我們的vue例項就可以愉快的使用起來

ps:插值表示式中的$t就是vue-i18n暴露給使用者的API

 

<template>

<div>

<h1>{{$t('message.hello')}}{{$i18n.locale}}</h1>

<div>{{$i18n.messages}}</div>

<div></div>

<el-button type="primary" @click="open">{{$t('btn.text')}}</el-button>

</div>

</template>

 

<script>

import { getProjectList } from "api/basicInfoService/project/index";

export default {

data() {

return {

projectOptions: null

}

},

created() {

getProjectList().then(response => {

this.projectOptions = response;

 

console.log(response)

this.$i18n.mergeLocaleMessage('zh', this.projectOptions)

}) .catch((err) => {

this.$message.error(this.$t('message.hello') + ':' + err.message)

});

},

methods: {

}

}

</script>

 

$i18n.locale來選擇性顯示相應的語言  專案用的是vue-cli框架,i18n.locale是自動監聽變化的

這裡this.$i18n.messages就是多語言切換的資料來源

vue-i18n的mergeLocaleMessage方法 新載入的資料合併到全域性

 

原始碼地址 https://github.com/kazupon/vue-i18n

原理解析 https://hachijiang.github.io/vue-i18n%E5%8E%9F%E7%90%86%E8%A7%A3%E6%9E%90/

https://www.liyu.fun/2018/03/13/electron/