Internationalization in Vue.js

Internationalization in Vue.js

在Vue.js里头实现国际化, 我们采用的是插件: vue-i18n

插件基础用法

  1. 引入及应用插件vue-i18n

    1
    2
    3
    4
    import Vue from 'vue'
    import VueI18n from 'vue-i18n'

    Vue.use(VueI18n)
  2. 导入国际化资源配置

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    // Ready translated locale messages
    const messages = {
    en: {
    message: {
    hello: 'hello world'
    }
    },
    ja: {
    message: {
    hello: 'こんにちは、世界'
    }
    }
    }

    // Create VueI18n instance with options
    const i18n = new VueI18n({
    locale: 'ja', // set locale
    messages, // set locale messages
    })
  3. 创建Vue实例, 并应用vue-i18n配置

    1
    new Vue({ i18n })  ...
  4. 使用

    1
    2
    3
    <el-button type="primary" class="login-btn" @click.native.prevent="submitLogin" :loading="logining">
    {{ $t('button.login') }}
    </el-button>

系统集成后的用法

lang目录存放国际化资源信息. 国际化文本存方于_[locale]_.json文件, 并且需要在 index.js 文件中注册. 注册方式:

1
2
3
4
5
6
7
8
9
import cn from './cn.json'
import en from './en.json'

...
const languages = {
cn: {language: "简体中文", message: cn},
en: {language: "English", message: en}
};
...

国际化资源文本的使用有以下三种方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- 方式一 -->
<el-button type="primary" class="login-btn" @click.native.prevent="submitLogin" :loading="logining">
{{ $t('button.login') }}
</el-button>

<!-- 方式二 -->
<el-input type="password" v-model="loginForm.password" :placeholder="$t('login.password')" />

<!-- 方式三 -->
submitLogin(ev) {
let i18n = this.$i18n;
alert(i18n.t('login.validation.username.require');
}

具体参考: vue-i18n