我有一个小型 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 和 this.$root.$i18n.locale 但它们似乎也不起作用。
此外,当我尝试访问来自区域设置文件夹中的 JSON 文件的消息的
[intlify] 在“nl”区域设置消息中找不到“message”键。
[intlify] 回退到用“en”语言环境翻译“message”键
[intlify] 在“en”区域设置消息中找不到“Message”键。
[intlify] 回退到使用“nl”语言环境翻译“message”键
我的问题是,我在哪里做错了什么,有没有办法摆脱当我尝试从区域设置文件夹访问 JSON 文件时收到的警告?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我正在使用组合,所以不能 100% 确定这对你有用,但这对我有用:
更改自
至
希望有帮助。 :)