intlify / nuxt3

Nuxt 3 Module for vue-i18n-next

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Question] How can I change locale programmatically ?

lastmirage opened this issue · comments

Hi

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

but I want to change it in <script setup> like this

<script setup> i18n.locale = 'en' // or locale from other resources </script>

how can I do that ?

commented

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';

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.

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)

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

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 Did you manage to access to the i18n instance from a plugin ?