How can I call a function when the language/locale changes while using i18n?
Should I use Vuex or does vue-i18n has a method that allows me to do that?
Is there a way to watch a change of the i18n's current locale?
Asked Answered
Please include more information about you are trying to do, e.g. what command are you trying to run with the vue cli? –
Premonish
You could watch $i18n.locale
for any changes but usually, you do change this kind of thing. What is your use-case for such need ?
watch: {
'$i18n.locale': function(newVal, oldVal) {
console.log('locale change', newVal)
}
}
This does not work. Nothing is triggered by changes on
i18n.locale
. To be clear, my i18n mechanism is working fine, only this watch is not. I tried the rule with and without the leading dollar sign. I'm on vue 2.6.12, vue-i18n 8.22.4 and vuex 3.6.2. I'm not downvoting this because versions could be the issue, but for the 13 of you that upvoted this, I would like to know how did this work. –
Gertie @Gertie not sure why this is not working for you, it all depends on how you implemented it I suppose. Usual way is to work with
$i18n
hence why the watcher should work. Still, if it's not feel free to ask a new question with a minimal reproducible example or at least all the relevant details regarding your configuration. –
Pockmark Not sure about your setup, but with Vue3 in SFC I am using it as follows:
New Way:
(changed according to @kissu's tip)
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
const { t, locale } = useI18n();
watch(locale, () => {
console.log('locale', locale.value);
});
</script>
It fires every time the locale changes (for example with a language toggle outside of the actual file/component).
Old Way:
<script setup lang="ts">
import i18n from '@/i18n';
const locale = ref(i18n.global.locale);
watch(locale, () => {
console.log('locale', locale.value);
});
</script>
If you want a try Composition API-y way of doing this, I recommend using
useI18n
and t
even: vue-i18n.intlify.dev/guide/advanced/composition.html –
Pockmark This worked for me (based on the "old way" @goldensoju mentioned):
const currentLocale = computed(() => i18n.global.locale)
watch(currentLocale, (value) => {
console.log(`locale change: ${value}`)
})
I needed it in a Nuxt 3 application using yup
. Managed to do it with custom plugin (it will be included automatically):
plugins/yup-18n.ts
import { setLocale } from 'yup';
import { de, en } from 'yup-locales';
export default defineNuxtPlugin((nuxtApp) => {
const locale = nuxtApp.vueApp.$nuxt.$i18n.locale;
// set yup locale initially
setLocale(locale.value === 'en' ? en : de);
// and after changes
watch(locale, () => {
setLocale(locale.value === 'en' ? en : de);
});
});
© 2022 - 2025 — McMap. All rights reserved.