1

我正在使用插件vue-i18n在 Nuxt.js 驱动的 SPA 中进行翻译。这允许轻松访问components中的消息,如下所示:

$t('footer.press')

但是如何在组件之外获得翻译?在我的具体情况下,我需要在商店操作中使用它们:

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

    (...)

    })

  }


这就是我在项目中包含 vue-i18n 插件的方式:

包.json

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

nuxt.config.js

…
plugins: [
        …
        '~/plugins/i18n',
        …
    ],
…
4

2 回答 2

2

您可以通过导入i18n来使用vue-i18n外部组件,然后使用i18n.global中的“ t ” 。

t ”不需要“ $ ”,您可以使用i18n.global.locale更改区域设置

import i18n from '../i18n';

const { t } = i18n.global;

i18n.global.locale = 'en-US'; // Change "Locale"

const data = { 
  name: t('name'), // "t" doesn't need "$"
  description: t('description'), // "t" doesn't need "$"
};
于 2021-09-26T09:22:33.143 回答
1

经过一番研究,我在 Vue 论坛上找到了一个可行的解决方案

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

像魅力一样为我工作!

于 2020-12-17T09:17:23.697 回答