DEV Community

d4g0
d4g0

Posted on

How to react to @nuxt-i18n locale changes inside the setup function

If you are using Nuxt v2, nuxt-i18n and you want to react to i18n object changes inside the setup function, let's say, a language change, this blog will teach you how.

I also cover how to use localized messages inside the setup function in this other article.

Let's say for instance, you want to craft a special url to point to other site, but you want to keep the current language of your user in the link:

setup(props, ctx) { // all the stuff is in the root const { root } = ctx; const mapedURL = ref(""); const baseUrl = "https://my.other-site.com"; function setUrl() { const isInSpanish = ctx.root.$i18n.localeProperties.code == "es"; if (isInSpanish) { mapedURL.value = baseUrl; } else { mapedURL.value = baseUrl + "/en/"; } } function triggerWatch() { // keep traking on language changes when page loads // hint: this dosen't work in edge properties like *.localeProperties.code watch(ctx.root.$i18n.localeProperties, (newV, oldV) => { setUrl(); }); } // init when page loads onMounted(() => { // this watch will brake in the server so ignore there if (!process.client) { return; } setUrl(); triggerWatch(); }); return { mapedURL } } 
Enter fullscreen mode Exit fullscreen mode

Tested in Nuxt v2 and nuxt-i18n v7. That's it folks.

Top comments (0)