国际化——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',    // 语言标识
  messages : {
    en: {
      message: {
        hello: 'hello world'
      }
    },
    cn: {
      message: {
        hello: '你好、世界'
      }
    }
  }
})
/*---------使用语言包-----------*/
const i18n = new VueI18n({
  locale: 'CN',    // 语言标识
  messages: {
    'CN': require('./assets/common/lang/cn'),   // 中文语言包
    'EN': require('./assets/common/lang/en')    // 英文语言包
  },
})

/*---------语言包内部语法star-----------*/
export const  message = {
      language:'语言',
      hello: '你好,世界'
}
/*---------语言包内部语法end-----------*/

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

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

单独组件的使用

  • 在单个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>


作者:前端小兵
链接:https://www.jianshu.com/p/0324115fcd4e
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值