安装i18n
vue add i18n
? The locale of project localization. zh // 首选语言 zh
? The fallback locale of project localization. en // 替代语言 en,首选语言中没有的会显示替代语言
? The directory where store localization messages of project. It's stored under
`src` directory. locales // 语言文件目录
? Enable locale messages in Single file components ? Yes // 是否允许在组件中使用 messages
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;
}
function getLanguage() {
if (localStorage && localStorage.locale) {
return localStorage.locale;
}
// 使用系统语言,如果语言文件中没有则使用 en
return (navigator.language || navigator.userLanguage).split("-")[0];
}
// locale
export default new VueI18n({
locale: getLanguage(),
fallbackLocale: "en",
messages: loadLocaleMessages(),
});
src/main.js
import Vue from 'vue'
import App from './App.vue'
import i18n from './i18n'
Vue.config.productionTip = false
new Vue({
i18n,
render: h => h(App)
}).$mount('#app')
语言文件目录
src/locales/en.json
{
"message": "Hello i18n !!"
}
src/locales/zh.json
{
"message": "你好 i18n !!"
}
多语言切换
{{ $t("hello") }}
:class="{ active: active === index }"
v-for="(lang, index) of langs"
:key="index"
@click="changeLanguage(lang.value)"
>
{{ lang.label }}
export default {
name: "HelloI18n",
// "English", "中文", "Das ist Deutsch", "En français"
data() {
return {
langs: [
{
label: "English",
value: "en",
},
{
label: "中文",
value: "zh",
},
{
label: "Das ist Deutsch",
value: "de",
},
{
label: "En français",
value: "fr",
},
],
};
},
computed: {
active() {
const index = this.langs.findIndex(
(item) => item.value === this.$i18n.locale
);
console.log(index);
return index;
},
},
methods: {
changeLanguage(lang) {
// 保存语言配置到localStorage
localStorage.setItem("locale", lang);
// 修改显示语言
this.$i18n.locale = lang;
// TODO 修改远程配置
},
},
created() {},
};
{
"en": {
"hello": "Hello i18n !!"
},
"zh":{
"hello":"你好, i18n !"
},
"fr":{
"hello":"Bonjour i18n!"
}
}
实现效果
d1xdbD.gif