How to get i18n locale in nuxt.config file (technologies: Nuxt 3, Vue 3, Vite)

154 Views Asked by At

How to get the equivalent to context.app.i18n.locale inside nuxt.config.ts file in Nuxt 3 ?

I am using "@nuxtjs/i18n": "^8.0.0-rc.5" (the @nuxtjs/i18n@next one).

Thank you in advance,

2

There are 2 best solutions below

0
On

Ii realized I couldn't, so I used a different strategy.

1
On

With Nuxt 3 I have created a Pinia store in the project and called it localeStore. This is the locale.ts file code for the store:

import { defineStore } from "pinia";

export const useLocaleStore = defineStore("locale", {
  state: () => ({    
  }),
  getters: {
    currentLocale: () => {
      return useNuxtApp().$i18n.locale.value;
    }
  },
  actions: {
    translate(key: string) {
      return useNuxtApp().$i18n.t(key);
    }
  }
});

Then, inside other .ts files in composables or utils or whatever, you can import the store and use its currentLocale getter or translate function:

import { useLocaleStore } from "~~/store/locale";

const localeStore = useLocaleStore();

function t(key: string) {
  return localeStore.translate(key);
}