vue-i18n
vue-i18n copied to clipboard
`const { t } = useI18n()` does not work
Reporting a bug?
the composable in vue3 for using i18n does not work with the createi18n or the api description is wrong. No translations are found if you create i18n in one file and try to use it with useI18n in a component. There is also no description for this scenario, all examples handle everything in one file.
Expected behavior
useI18n should use the previous created instance of createi18n and find the translations.
Reproduction
import { createApp } from 'vue';
import { createI18n } from 'vue-i18n';
import messages from 'src/i18n';
const i18n = createI18n({
locale: 'en',
messages,
});
const app = createApp()
app.use(i18n);
<template><div>hello world</div></template
<script setup>
import { useI18n } from 'vue-i18n';
const { t } = useI18n({ useScope: 'global' });
const something = t('failure'); // <-- Error
</script>
System Info
System:
OS: Windows 10 10.0.19042
CPU: (16) x64 Intel(R) Core(TM) i7-10700 CPU @ 2.90GHz
Memory: 3.35 GB / 15.75 GB
Binaries:
Node: 14.17.3
Yarn: 1.22.4
npm: 7.20.6
Browsers:
Edge: Spartan (44.19041.423.0), Chromium (92.0.902.67)
Internet Explorer: 11.0.19041.1
npmPackages:
vue-i18n: ^9.1.8 => 9.1.9
vue-router-mock: ^0.0.3 => 0.0.3
Screenshot
No response
Additional context
No response
Validations
- [X] Read the Contributing Guidelines
- [X] Read the Documentation
- [X] Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- [X] Check that this is a concrete bug. For Q&A open a GitHub Discussion
Thank you for your reporting!
Unfortunately, I could not reproduce this issue. We need minimum reproduction codes Could you provide it to us, please?
import { createApp } from 'vue';
import { createI18n } from 'vue-i18n';
import messages from 'src/i18n';
const i18n = createI18n({
legacy: false,
locale: 'en',
messages,
});
const app = createApp()
app.use(i18n);
not sure if legacy: true is the default
The problem occurred when I was using lerna management package,seems this code do not get locales correct when use lerna, I log this messages of en is undefined. if i set messges inline the file, it works well. So there must be a problem with the locales file path when use lerna manage package.
function loadLocaleMessages(): LocaleMessages<VueMessageType> {
const locales = require.context('./locales', true, /[A-Za-z0-9-_,\s]+\.json$/i)
const messages: LocaleMessages<VueMessageType> = {}
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).default
}
})
return messages
}
Close in-activity
We need a solution to this issue, but we need the minimue reproduction code that can actually confirm the issue with anyone. we need a github repo or stackbliz where anyone can reproduce the issue.
If you would be faced this issue agina, please you would open the new issue. thanks!