國(guó)際化——Vue-i18n的使用

Vue-i18n安裝

  • npm install vue-i18n --save

Vue-i18n的使用

  • 在入口main.js文件配置使用
import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n);
/*---------基本使用-----------*/
const i18n = new VueI18n({
  locale: 'CN',    // 語(yǔ)言標(biāo)識(shí)
  messages : {
    en: {
      message: {
        hello: 'hello world'
      }
    },
    cn: {
      message: {
        hello: '你好、世界'
      }
    }
  }
})
/*---------使用語(yǔ)言包-----------*/
const i18n = new VueI18n({
  locale: 'CN',    // 語(yǔ)言標(biāo)識(shí)
  messages: {
    'CN': require('./assets/common/lang/cn'),   // 中文語(yǔ)言包
    'EN': require('./assets/common/lang/en')    // 英文語(yǔ)言包
  },
})

/*---------語(yǔ)言包內(nèi)部語(yǔ)法star-----------*/
export const  message = {
      language:'語(yǔ)言',
      hello: '你好,世界'
}
/*---------語(yǔ)言包內(nèi)部語(yǔ)法end-----------*/

/*---------掛載全局使用-----------*/
new Vue({
  el: '#app',
  i18n,
  router,
  template: '<App/>',
  components: { App }
})

/*---------vue組件模板的使用-----------*/
 <template>
        <p>{{ $t("message.hello") }}</p>
    </template>

單獨(dú)組件的使用

  • 在單個(gè)vue組件中使用,要用到i18n自定義塊,需要配置webpack文件webpack.base.conf.js
module.exports = {
  // ...
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: {
            // you need to specify `i18n` loaders key with `vue-i18n-loader` (https://github.com/kazupon/vue-i18n-loader)
            i18n: '@kazupon/vue-i18n-loader'
          }
        }
      },
      // ...
    ]
  },
  // ...
}
  • 示例
<i18n>
{
  "en": {
    "hello": "hello world!"
  },
  "ja": {
    "hello": "你好,世界!"
  }
}
</i18n>

<template>
  <div id="app">
    <label for="locale">locale</label>
    <select v-model="locale">
      <option>en</option>
      <option>ja</option>
    </select>
    <p>message: {{ $t('hello') }}</p>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () { return { locale: 'en' } },
  watch: {
    locale (val) {
      this.$i18n.locale = val
    }
  }
}
</script>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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