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.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

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

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay