随着全球化的发展,多语言和国际化越来越成为一个网站或应用的必要功能之一。Vue作为一款流行的前端框架,在这方面也有着灵活的解决方案。本文将介绍如何使用Vue实现多语言和国际化。
一、安装Vue-i18n
Vue-i18n是Vue.js的国际化插件,可以帮助我们实现多语言和国际化。首先需要在项目中安装Vue-i18n。
npm install vue-i18n --save
二、创建语言文件
在项目中创建一个i18n文件夹,用于存放语言文件。
在i18n文件夹中创建一个名为index.js的文件,用于配置Vue-i18n。
import Vue from 'vue';
import VueI18n from 'vue-i18n';
Vue.use(VueI18n);
const i18n = new VueI18n({
locale: 'en', // 默认使用英文
messages: {
en: require('./en.json'),
zh: require('./zh.json'),
},
});
export default i18n;
上述代码中,locale表示当前使用的语言,默认使用英文。messages表示使用的语言文件,这里分别引入了en.json(英文)和zh.json(中文)。
现在可以在i18n文件夹中创建en.json和zh.json文件,并编写语言内容。
en.json
{
"hello": "Hello",
"world": "World",
"welcome": "Welcome"
}
zh.json
{
"hello": "你好",
"world": "世界",
"welcome": "欢迎"
}
三、使用Vue-i18n
在组件中使用Vue-i18n非常简单,只需要在模板中添加$tc(翻译)或$t(格式化)即可。
<template>
<div>
<p>{{ $t('hello') }}</p>
<p>{{ $tc('world', 1) }}</p>
<p>{{ greeting }}</p>
</div>
</template>
<script>
import i18n from '@/i18n';
export default {
computed: {
greeting() {
return this.$t('welcome', { name: 'Vue' });
},
},
created() {
// 设置语言为中文
i18n.locale = 'zh';
},
};
</script>
上述代码中,$t和$tc都可以用于翻译,区别在于$t可以进行格式化,$tc可以根据参数进行复数化。这里还演示了computed属性中使用$t方法,以及在组件created生命周期中修改语言。
四、使用Vue CLI插件
Vue CLI提供了官方插件vue-cli-plugin-i18n,可以快速集成多语言和国际化。
首先需要安装插件。
vue add i18n
安装成功后,会在项目中生成locales文件夹,用于存放语言文件。
修改src/i18n.js文件。
import Vue from 'vue';
import VueI18n from 'vue-i18n';
Vue.use(VueI18n);
function loadLocaleMessages() {
const locales = require.context('@/locales', true, /[A-Za-z0-9-_,s]+.json$/i);
const messages = {};
locales.keys().forEach((key) => {
const matched = key.match(/([A-Za-z0-9-_]+)./i);
if (matched && matched.length > 1) {
const locale = matched[1];
messages[locale] = locales(key);
}
});
return messages;
}
export default new VueI18n({
locale: process.env.VUE_APP_I18N_LOCALE || 'en',
fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
messages: loadLocaleMessages(),
silentFallbackWarn: true,
});
上述代码中,loadLocaleMessages函数用于自动加载locales文件夹中的语言文件,并返回messages对象。此外,还可以通过环境变量VUE_APP_I18N_LOCALE和VUE_APP_I18N_FALLBACK_LOCALE设置默认语言和回退语言。
.........................................................