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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay