nuxt3 icon indicating copy to clipboard operation
nuxt3 copied to clipboard

[Question] How can I change locale programmatically ?

Open lastmirage opened this issue 3 years ago • 6 comments

Hi

as described in doc, I can change locale with $i18n.locale in component template

but I want to change it in

how can I do that ?

lastmirage avatar Jul 08 '22 09:07 lastmirage

This is what I do since it should get the instance of i18n since this package is only a wrapper for that vue-i18n. Not sure if its documented but it works for me @lastmirage

import { useI18n } from 'vue-i18n';
const { locale } = useI18n();
locale.value = 'es';

jvrsolis avatar Jul 10 '22 21:07 jvrsolis

This is what I do since it should get the instance of i18n since this package is only a wrapper for that vue-i18n. Not sure if its documented but it works for me @lastmirage

import { useI18n } from 'vue-i18n';
const { locale } = useI18n();
locale.value = 'es';

works for me too, u can get the messages too if u used const { t } = useI18n(). console log useI18n to see the full functions.

MuhammadM1998 avatar Jul 13 '22 08:07 MuhammadM1998

It works for me too but I have a typescript error:

Module '"vue-i18n"' has no exported member 'useI18n'. Did you mean to use 'import useI18n from "vue-i18n"' instead?ts(2614)

femtozer avatar Jul 13 '22 19:07 femtozer

It works for me too but I have a typescript error:

Module '"vue-i18n"' has no exported member 'useI18n'. Did you mean to use 'import useI18n from "vue-i18n"' instead?ts(2614)

Did you set your legacy attribute to false in your i18n config? It's required if you wanted to use the composition api.

more info: https://vue-i18n.intlify.dev/guide/advanced/composition.html

MuhammadM1998 avatar Jul 15 '22 08:07 MuhammadM1998

How can i change locale programmatically from plugins?

If i use the above code throws an error:

in: plugins/locale.ts

import { useI18n } from 'vue-i18n';

export default defineNuxtPlugin(async (nuxtApp) => {
    const { locale } = useI18n();
    locale.value = 'es';
});

[h3] [unhandled] H3Error: Must be called at the top of a setup function

salomonsanz avatar Aug 09 '22 08:08 salomonsanz

@salomonsanz Did you manage to access to the i18n instance from a plugin ?

copostic avatar Sep 05 '22 16:09 copostic