我想实现一个性别特定的场所管理系统,这意味着对于一些语言,如希伯来语和阿拉伯语,文本对于男性和女性是不同的。所以我做的是,为男性和女性创建了单独的文件。这是我的目录结构-
locales
female
he.json
ar.json
male
he.json
ar.json
en.json现在,我希望对于女性用户,应该从女性文件夹中选择区域设置文件,对于男性用户,应该从男性文件夹中选择区域设置文件。在英语的情况下,文件"en.json“对于男性和女性都是相同的。
性别详细信息存储在Vue状态中,因此在i18n.js文件中,我检查了用户的性别并更新了locale文件的路径。这是我的i18n.js文件-
import Vue from "vue";
import VueI18n from "vue-i18n";
import { DEFINES } from "@/defines";
import { store } from "@/store";
Vue.use(VueI18n);
function getRelevantLocale() {
if (
!Object.entries(store.state.user.user).length ||
store.state.user.user.user_lang === "en"
) {
return require.context("./locales", true, /[A-Za-z0-9-_,\s]+\.json$/i);
} else if (store.state.user.user.gender === "female") {
return require.context(
"./locales/female",
true,
/[A-Za-z0-9-_,\s]+\.json$/i,
);
} else if (store.state.user.user.gender === "male") {
return require.context("./locales/male", true, /[A-Za-z0-9-_,\s]+\.json$/i);
}
}
export const loadLocaleMessages = () => {
const locales = getRelevantLocale();
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 const i18n = new VueI18n({
messages: loadLocaleMessages(),
locale: DEFINES.I18N_LOCALE || "en",
fallbackLocale: DEFINES.I18N_FALLBACK_LOCALE || "en",
silentFallbackWarn: true,
});问题是,当性别或语言改变时,区域设置路径不会更新,即,如果语言是希伯来语,性别是女性,而我转向具有相同性别的语言英语,则在我重新加载页面之前,i18n不会从"locales/en.json“中选取正确的文件。
有没有人能提个建议?
发布于 2021-09-08 03:58:04
我找到了一个解决方案。
每当更改区域设置时,都会更新该区域设置的消息。
假设设置了locale "en“,"en”的消息来自"locales/en.json“文件,现在我们切换到带有任何性别的locale "he”,比如“say”,那么"he“的消息应该来自”locales/say/he.json“文件。
要做到这一点,只需在切换语言环境后添加以下行-
// Set locale
i18n.locale = "he";
// Update messages for this locale
i18n.setLocaleMessage("he", loadLocaleMessages()["he"]);https://stackoverflow.com/questions/69073667
复制相似问题