Vue i18n -不能动态更改区域设置



我有一个小的vue应用程序,我想实现vue-i18n插件,使我的应用程序多语言。我已经从vue命令行安装了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访问区域设置。但是,这对我来说不起作用,这就是我尝试实现它的方式:

<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]:本机事件处理程序执行过程中未处理的错误

Uncaught TypeError: Cannot set properties of undefined (setting ."语言环境")

我已经尝试了一些其他的解决方案,如i18n。区域设置和这个$root.$i18n。区域设置,但它们似乎也不起作用。

另外,当我试图访问

{{t("message")}}

从消息来自JSON文件从locale文件夹我得到这些警告:

[intlify]在'nl' locale消息中没有找到'message'键。

[intlify]退回到用'en' locale翻译'message'键

[intlify]在'en'区域设置消息中没有找到'message'键。

[intlify]退回到用'nl' locale翻译'message'键

我的问题是,我在哪里做错了什么,有没有办法摆脱警告,我有当我试图访问JSON文件从locale文件夹?

我正在使用合成,所以不能100%确定这是否适用于您,但这对我来说是可行的:

从改变

i18n.locale = selectedLocale

i18n.global.locale = selectedLocale

希望有帮助。:)

最新更新