今天我们将介绍如何在我们的Vue应用程序中实现 i18n、国际化。我们将使用由Kazuya Kawaguchi编写的vue-i18n 插件,他是Vue.js的核心开发人员之一。
在我们的网络应用程序中提供国际化支持对于让全球受众使用它们至关重要。虽然全球有很多人会说或理解英语,但通过添加 i18n 支持,我们正在向更广泛的受众开放我们的应用程序。
应用程序设置
我们首先假设您已经创建了一个简单的Vue应用程序。现在我们将使用您喜欢的方法添加vue-i18n插件:
# Yarn
$ yarn add vue-i18n
# npm
$ npm install vue-i18n
# Vue CLI 3.x+
$ vue add i18n
下面我们将设置基本的Vue应用程序。您会注意到我们只是将一些东西整合在一起,还没有真正使用插件,但这会让您在添加i18n支持之前了解我们的应用程序的行为。
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import App from './App.vue';
Vue.use(VueI18n);
new Vue({
render: h => h(App),
}).$mount('#app');
<template>
<div id="app">
<HelloGator />
</div>
</template>
<script>
import HelloGator from './components/HelloGator.vue'
export default {
name: 'App',
components: {
HelloGator
}
}
</script>
<template>
<div>Hello, Gator</div>
</template>
<script>
export default { name: 'Gator' }
</script>
格式化
所述VUE-I18N插件允许用于与简单的单托架语法串的格式。在这里,我们添加了一个messages
对象,该对象将为我们的应用程序提供应根据当前locale
. 我们初始化一个new VueI18n
实例并将其传递给我们的Vue实例。
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import App from './App.vue';
Vue.use(VueI18n);
const messages = {
en: {
message: {
hello: 'Hello, {name}!'
}
},
de: {
message: {
hello: 'Guten Tag, {name}!'
}
}
};
const i18n = new VueI18n({
locale: 'en',
messages
});
new Vue({
render: h => h(App),
i18n
}).$mount('#app');
为了在组件中使用我们的应用程序字符串,vue-i18n提供了一个函数$t()
,该函数将根据给定键的当前语言环境提供翻译。在这种情况下,我们请求message.hello
字符串并为其提供模板变量name
。
<template>
<div>{{ $t('message.hello', { name: 'Gator' }) }}</div>
</template>
由于我们默认为en
语言环境,您应该会Hello, Gator!
在屏幕上看到呈现的内容。
更改语言环境
现在您可能想知道我们如何访问或更改我们为其添加了应用程序字符串的其他语言环境。我们de
在初始设置中添加了对德语语言环境的支持。所述VUE-I18N插件提供部件能够访问i18n
通过实例$i18n
变量。只需设置$i18n.locale
切换到新的语言环境。
让我们添加一个组件,允许我们即时切换语言环境:
<template>
<div>
<select v-model="$i18n.locale">
<option
v-for="(lang, i) in langs"
:key="`lang-${i}`"
:value="lang"
>
{{ lang }}
</option>
</select>
</div>
</template>
<script>
export default {
name: 'SelectLocale',
data() {
return { langs: ['en', 'de'] }
}
}
</script>
<template>
<div id="app">
<SelectLocale />
<HelloGator />
</div>
</template>
import HelloGator from './components/HelloGator.vue'
import SelectLocale from './components/SelectLocale.vue'
export default {
name: 'App',
components: {
HelloGator,
SelectLocale
}
}
现在,在应用程序重新加载后,您将看到一个<select>
允许我们更改当前语言环境的元素。尝试将选定的语言环境更改为de
以查看呈现的输出如何更改为Guten Tag, Gator!
。
包起来
该VUE-i18n的插件是一个很好的解决方案能够轻松地添加国际化,以我们现有的Vue应用程序。它是一个出色的、可用于生产的库,具有许多功能,可以涵盖大多数(如果不是全部)i18n 问题。与往常一样,请务必查看插件的文档以了解它必须提供的所有功能。