Answer the question
In order to leave comments, you need to log in
How to use en.json/ru.json to translate an application?
Hello, having created a Vue 3 CLI + i18n project, I found that i18n does not display translations that are in the locales folder, and those added as a tag work properly. For example
//en.json
{
"message": "hello i18n !!"
}
<template>
<p>{{ t("message") }}</p>
<p>{{ t("hello") }}</p>
</template>
<script>
//HelloWorld component
import { defineComponent } from "vue";
import { useI18n } from "vue-i18n";
export default defineComponent({
name: "HelloWorld",
setup() {
const { t } = useI18n({
inheritLocale: true,
useScope: "local",
localStorage: true,
});
alert(t("message"));
// Something todo ..
return { t };
},
});
</script>
<i18n>
{
"en": {
"hello": "Hello i18n in SFC!"
}
}
</i18n>
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(),
});
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question