我有一个小型 vue 应用程序,我想在其中实现 vue-i18n 插件以使我的应用程序多语言。我已经从 vue cli 安装了 vue-i18n 插件。我有两个语言环境,一切都按预期工作 - 每当我手动将语言环境从 .env 文件更改为所需语言时,应用程序中的语言也会更改。但是,每当我尝试使用前端上的按钮更改它时,我都会失败这样做。
这是我的 i18n.js 文件中的内容:
import { createI18n } from 'vue-i18n'
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 createI18n({
legacy: false,
locale: process.env.VUE_APP_I18N_LOCALE || 'en',
fallbackLocale: process.env.VUE_APP_I18N_FALLBACK_LOCALE || 'en',
messages: loadLocaleMessages()
})
这是在 .env 文件中:
VUE_APP_I18N_LOCALE=en
VUE_APP_I18N_FALLBACK_LOCALE=en
这是我看到的教程中的代码,他们通过以下方式访问语言环境this.$i18n.locale
,但这对我不起作用,这就是我尝试实现它的方式:
<template>
<div class="hello">
<h1>Hello World</h1>
<h2>{{ t("hello") }}</h2>
<h2>{{ t("message") }}</h2>
<button @click="SetLocale('en')">EN</button>
<button @click="SetLocale('nl')">NL</button>
</div>
</template>
<script>
import { useI18n } from "vue-i18n";
export default {
name: "HelloWorld",
setup() {
const { t } = useI18n({
inheritLocale: true,
useScope: "local",
});
// Something todo ..
return { t };
},
methods: {
SetLocale(locale) {
console.log(locale);
this.$i18n.locale = locale;
},
},
};
</script>
<i18n>
{
"en": {
"hello": "Hello i18n in English! (from component)"
},
"nl": {
"hello": "Hello i18n in Dutch! (from component)"
}
}
</i18n>
我收到的错误是:
[Vue warn]:执行本机事件处理程序期间出现未处理的错误
未捕获的类型错误:无法设置未定义的属性(设置“区域设置”)
我尝试过其他一些解决方案,例如i18n.locale
and this.$root.$i18n.locale
但它们似乎也不起作用。
另外,当我尝试访问<h2>{{ t("message") }}</h2>
从中message
来自 locales 文件夹中的 JSON 文件我收到这些警告:
[intlify] 在“nl”语言环境消息中找不到“message”键。
[intlify] 回退以使用“en”语言环境翻译“message”键
[intlify] 在“en”区域设置消息中找不到“message”键。
[intlify] 回退以使用“nl”语言环境翻译“message”键
我的问题是,我在哪里做错了什么,有没有办法摆脱当我尝试从以下位置访问 JSON 文件时出现的警告:locales
文件夹>