8

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?

kissu
  • 40,416
  • 14
  • 65
  • 133
Serio
  • 465
  • 4
  • 15
  • Please include more information about you are trying to do, e.g. what command are you trying to run with the vue cli? – Noah May Apr 18 '21 at 04:12

2 Answers2

15

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)
  }
}
kissu
  • 40,416
  • 14
  • 65
  • 133
  • 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. – Ricardo May 23 '22 at 07:58
  • @Ricardo 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 [repro] or at least all the relevant details regarding your configuration. – kissu May 23 '22 at 08:07
2

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>
goldensoju
  • 606
  • 1
  • 6
  • 14
  • If you want a try Composition API-y way of doing this, I recommend using `useI18n` and `t` even: https://vue-i18n.intlify.dev/guide/advanced/composition.html – kissu Oct 20 '22 at 08:36