1

I want to use a vue-i18n to translate error codes into error messages. To show this method I created a function a ts file looking like this.

import {ElMessage} from "element-plus";
import {useI18n} from "vue-i18n";


export function defaultErrorHandler(error) {
    const t = useI18n({
        useScope: 'global',
        inheritLocale: true
    }).t;

    if (error.response == undefined) {
        ElMessage({
            message: '...',
            type: 'error',
        })
    } else if (error.response.status == 403) {
        store.commit('logout')
        doAuthRedirect()
    } else if (error.response.status == 400 || error.response.data != undefined) {
        ElMessage({
            message: t(error.response.data, t("unknown response error from server, notify administrator")),
            type: 'error',
        });
    } else {
        ElMessage({
            message: '...',
            type: 'error',
        })

    }
}

Result in:

Uncaught (in promise) SyntaxError: Must be called at the top of a `setup` function
createCompileError message-compiler.esm-bundler.js:32
createI18nError vue-i18n.esm-bundler.js:66
useI18n vue-i18n.esm-bundler.js:2037
defaultErrorHandler index.ts:6

It is not in context of a vue component.
But how do i obtain an instance of i18n ?

This the i18n setup code from main.ts

const i18n = createI18n({
    legacy: false,
    locale: 'de',
    messages: {
        'de': messagesDe
    }
});

const app = createApp(App)
app.use(store)
app.use(router)
app.use(i18n)

Thank you for your help

Ace of Spade
  • 388
  • 3
  • 22
  • is the i18next tag intensional? if you're referring to vue + i18next, then you may have a look at: https://github.com/i18next/i18next-http-backend/tree/master/example/vue https://github.com/panter/vue-i18next/issues/123#issuecomment-855383961 – adrai Feb 01 '22 at 12:57
  • Is there a usage outside a vue component? – Ace of Spade Feb 01 '22 at 13:03
  • outside of a component just import i18next and call i18next.t().... but I don't know if this is what you're looking for – adrai Feb 01 '22 at 13:04
  • @adrai It works but I have to install i18next and I have to redo all the config done in main.ts . It searms like a hack to me. – Ace of Spade Feb 01 '22 at 13:25

1 Answers1

0

useI18n relies on the Vue apparatus. I think your best bet is to pass in the Composer instance in your defaultErrorHandler function.

For those using Typescript...

import type { Composer } from 'vue-i18n';
...

export function hydrateTask(task: Task, v18n: Composer):ClientTask {
  return Object.assign(t, {
    description: v18n.t('...'), // just like t(...) 
  });
}

Or per the related discussion here, you can store and export the I18n instance you create in your createI18n(...) function. Then import it wherever you need it.

Robert
  • 1,220
  • 16
  • 19