美文网首页
vue-i18n使用规则

vue-i18n使用规则

作者: 莫伊剑客 | 来源:发表于2021-03-29 10:03 被阅读0次

安装

npm install vue-i18n
// 或者
yarn add vue-i18n

基础设置

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

export default new VueI18n({
  // 设置语言
  locale:'tw',
  // 设置翻译信息
  messages:{
    en: {
      messag:{
        applyspecialmeal:'xxxxxx',
        hello: '{0} world'
      },
      hello: 'hello world',
      phello: '{msg} world'
    },
    tw: {
      hello: 'こんにちは、世界',
      message:{
        hello: '%{msg} world'
      }
    }
  }
})

vue挂载

import Vue from 'vue';
import App from './App';
//导入自己设置好的i8n
import i18n from './assets/i18n';

export const app = new Vue({
  el: '#app',
  router,
  store,
  // 挂载i18n
  i18n,
  components: {App},
  template: '<App/>'
});

页面调用

// locale==='en'时
// 直接翻译
<p>{{$t('hello')}}</p> //输出结果:hello world

// 列表格式
<p>{{ $t('message.hello', ['hello']) }}</p> //输出结果:hello world
<p>{{ $t('message.hello', {'0': 'hello'}) }}</p> //输出结果:hello world

// 具名格式
<p>{{$t('phello',{msg:'xxHello'})}}</p> //输出结果:xxHello world

// HTML 格式化
<p v-html="$t('message.hello')"></p>

// locale==='tw'时
// 支持 ruby on rails 的 i18n 格式
<p>{{ $t('message.hello', { msg: 'hello' }) }}</p>

i18n自定义格式化

// 实现自定义格式
class CustomFormatter {
     constructor (options) {
       // ...
     }

     //
     // 插值
     //
     // @param {string} 信息
     //   列表或具名格式的字符串。
     //   例如:
     //   - 具名格式:'Hi {name}'
     //   - 列表格式:'Hi {0}'
     //
     // @param {Object | Array} 值
     //   `message` 插值的值
     //   使用 `$t`, `$tc` 和 `i18n` 函数式组件传递值。
     //   e.g.
     //   - $t('hello', { name: 'kazupon' }) -> 传递值:Object `{ name: 'kazupon' }`
     //   - $t('hello', ['kazupon']) -> 传递值:Array `['kazupon']`
     //   - `i18n` 函数式组件 (组件插值)
     //     <i18n path="hello">
     //       <p>kazupon</p>
     //       <p>how are you?</p>
     //     </i18n>
     //     -> 传递值:Array (included VNode):
     //        `[VNode{ tag: 'p', text: 'kazupon', ...}, VNode{ tag: 'p', text: 'how are you?', ...}]`
     //
     // @return {Array<any>}
     //   插值,你需要返回以下内容:
     //   - 当使用 `$t` 或 `$tc` 数组中应该是字符串。
     //   - 当使用 `i18n` 函数式组件时 数组中应包含 VNode 对象。
     //
     interpolate (message, values) {
       // 在这里实现插值逻辑
       // ...

       // 返回插值数组
       return ['resolved message string']
     }
}

// 注册 `formatter` 选项
const i18n = new VueI18n({
  locale: 'en-US',
  formatter: new CustomFormatter(/* 这里是构造函数选项 */),
  messages: {
    'en-US': {
      // ...
    },
    // ...
  }
})

// 启动!
new Vue({ i18n }).$mount('#app')

更多规则请参考i8n官方网站

相关文章

网友评论

      本文标题:vue-i18n使用规则

      本文链接:https://www.haomeiwen.com/subject/wdivhltx.html