DEV Community

d4g0
d4g0

Posted on

6 4

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay