Search code examples
vue.jsinternationalizationnuxt.jsvue-i18nnuxt-i18n

Nuxt.js - How do I use vue-i18n outside components?


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',
        …
    ],
…

Solution

  • 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!