3

I'm using the plugin vue-i18n for translations in a Nuxt.js-powered SPA. This allows easy access to messages within components, like this:

$t('footer.press')

But how do I get translations outside components? In my specific case, I need them in a store action:

export const actions = {

  async myAction({ commit, state, rootState, rootGetters }, options) {

    (...)

    const message = $t("example.message.key")             // doesn't work, undefined
    const message1 = this.$i18n.t("example.message.key")  // doesn't work, undefined

    (...)

    })

  }


This is how I include the vue-i18n plugin in the project:

package.json

…
 "dependencies": {
        …
        "vue-i18n": "^8.18.2",
        …
    },
…

nuxt.config.js

…
plugins: [
        …
        '~/plugins/i18n',
        …
    ],
…
gru
  • 2,319
  • 6
  • 24
  • 39

2 Answers2

1

After some research, I found a working solution on the Vue Forum here:

const message = this.app.i18n.t("example.message.key")

Works for me like a charm!

gru
  • 2,319
  • 6
  • 24
  • 39
  • 1
    There need to be explain, how you manage to to have `app.i18n` available as it will crash (ErrorType) when call `this.app.i18n` – Osify Mar 16 '21 at 07:20
  • @Osify I added more info to the question, hope this helps. – gru Mar 17 '21 at 08:09
  • thanks for update, I think, it's not matched to my case, I am using nuxt-i18n module, I write some javascript helper as an util outside the component and which suppose to call it when need in Vue component stuffs, I still cannot make the translation done in the helper js, either via this.app, via Vue.i18n etc. – Osify Mar 18 '21 at 06:54
  • @Osify To leverage reactivity system, your helper must return a i18n key identifier which will be used inside the downstream component. Therefore, when the current locale change at runtime, you get instantly new translations ! – scbj Apr 15 '21 at 14:17
0
this.$t('logInWongCredentials')

(nuxt)

Jiro Matchonson
  • 875
  • 1
  • 17
  • 24