I have a small vue application in which I want to implement the vue-i18n plugin to make my application multilingual. I have installed vue-i18n plugin from vue cli. I have two locales and everything works as expected - whenever I manually change the locale from the .env file to the desired language, the language in the application also changes. However, whenever I try to change it using the buttons on the frontend, I fail to do so.
This is the content in my i18n.js file:
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() })
This is in the .env file:
VUE_APP_I18N_LOCALE=en VUE_APP_I18N_FALLBACK_LOCALE=en
This is the code from the tutorials I saw, they access the locale via this.$i18n.locale, however, this doesn't work for me, this is how I tried to implement it:
<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>
The error that occurs when clicking the button is:
[Vue warn]: Unhandled error during execution of native event handler
Uncaught TypeError: Cannot set property of undefined (set 'Locales')
I tried some other solutions like i18n.locale and this.$root.$i18n.locale but they don't seem to work either.
Additionally, when I try to access the
[intlify] The 'message' key was not found in the 'nl' locale message.
[intlify] Fallback to translating the "message" key with the "en" locale
[intlify] The 'Message' key was not found in the 'en' locale message.
[intlify] Fallback to using the "nl" locale to translate the "message" key
My question is, where am I doing something wrong and is there a way to get rid of the warning I get when I try to access a JSON file from the locale folder?
I'm using combo, so not 100% sure this will work for you, but this worked for me:
Changed from
to
Hope it helps. :)