Reputation: 618
I'm trying to internationalize my Vue3 (with Vite setup) project with @intlify/vite-plugin-vue-i18n
and im using <script setup>
I keep getting Uncaught TypeError: i18n.global is undefined
but everthing seems correct. I've even tried original code from offical document which you can find here
No matter what i do, Vue or i18n cannot find global
property of i18n.
So my i18n.js is like this:
import { nextTick } from "vue";
import { createI18n } from "vue-i18n";
import axios from "axios";
import tr from "../src/locales/tr.json";
import en from "../src/locales/en.json";
export const SUPPORT_LOCALES = ["tr", "en"];
export function setupI18n(options = { locale: "tr" }) {
const i18n = createI18n(options);
setI18nLanguage(i18n, options.locale);
return i18n;
}
export function setI18nLanguage(i18n, locale) {
if (i18n.mode === "legacy") {
i18n.global.locale = locale;
} else {
i18n.global.locale.value = locale;
}
axios.defaults.headers.common["Accept-Language"] = locale;
document.querySelector("html").setAttribute("lang", locale);
}
export async function loadLocaleMessages(i18n, locale) {
const messages = await import(
/* webpackChunkName: "locale-[request]" */ `./locales/${locale}.json`
);
// set locale and locale message
i18n.global.setLocaleMessage(locale, messages.default);
return nextTick();
}
const i18n = createI18n({
legacy: false,
locale: "tr",
fallbackLocale: "tr",
globalInjection: true,
messages: {
tr,
en,
},
});
export default i18n;
component.vue
<script setup>
import { ref, onBeforeMount } from 'vue'
import { useI18n } from 'vue-i18n'
import { SUPPORT_LOCALES, setupI18n, setI18nLanguage, loadLocaleMessages } from '../../i18n.js'
const { locale } = useI18n() // same as `useI18n({ useScope: 'global' })`
const currentLocale = ref(locale.value)
function selectLanguage(language) {
// locale.value = language.target.value
loadLocaleMessages()
}
onBeforeMount(() => {
setI18nLanguage(currentLocale.value)
})
</script>
Upvotes: 1
Views: 4366
Reputation: 2626
What works for me is adding import i18n from '@/i18n';
to the script setup in the vue component. Then I can access the i18n.global
object.
Upvotes: 7