How can I lazyload translation files with $axios?

JkmAS
0
JkmAS
commented 2 months ago

I want to fetch the translation files with nuxt-axios from lang file, but the $axios is always undefined. I have tried several ways, but without success (https://github.com/nuxt-community/axios-module/issues/28#issuecomment-340743659). Is it possible to inject the app/context variable into lang file (e.g. en.js)? I just want to avoid two instances/configurations of axios in my nuxt project.

Thx.

My en.js lang file:

export default () => {
    return new Promise((resolve, reject) => {
        // call $axios to fetch the translations
    });
}

Example of conf:

export const i18n = {
    lazy: true,
    langDir: 'lib/lang/',
    locales: [
        { code: 'en', iso: 'en-US', file: 'en.js' },
        { code: 'fr', iso: 'fr-FR', file: 'fr.js' },
        { code: 'es', iso: 'es-ES', file: 'es.js' }
    ],
...
0
felixdenoix
5
felixdenoix
commented 6 days ago

Hi @JkmAS !
I'm working on a similar issue at the moment!
One solution that i found is to use the beforeLanguageSwitch hook in a plugin to fetch data before changing the language:

export default function ({ app }) {
    // beforeLanguageSwitch called right before setting a new locale
    app.i18n.beforeLanguageSwitch = (oldLocale, newLocale) => {
        app.i18n.setLocaleMessage('newLocale', {
            page: 'English text '
        })
        console.log(oldLocale, newLocale)
    }

    // onLanguageSwitched called right after a new locale has been set
    app.i18n.onLanguageSwitched = (oldLocale, newLocale) => {
      console.log(oldLocale, newLocale)
    }
}
0
Informations
Question โ€ข Unresolved
#c140 - Created 2 months ago