2

我的问题有点具体。我在这个项目中使用 Vuex 和 Nuxt。对于依赖项,我们使用 i18n-nuxt 但不知何故我不能在 $store 中使用 $t('some.translation') 而在组件中它工作得很好。我尝试了我能想象到的所有可能的组合,但结果仍然导致我出现同样的错误。

ReferenceError $t is not defined 或者 Cannot read the property of i18n

所以在这种情况下,我可以使用一些帮助来解决这个问题,或者如果有人向我展示如何使用 i18n 作为过滤器,那将是完美的。(我认为这是唯一的方法。)

例如,此代码块来自 $store.state

  sortMethods: [
{ id: 'airline', name: this.i18n.$t('Airline'), asc: 'A', desc: 'Z', defaultDirection: 'asc' },

您可以想象我无法将它们翻译到它们所在的位置。

4

2 回答 2

2

可以t使用this.$i18n.t. 前任。:

export const mutations = {
  foo() {
    console.log(this.$i18n.t("bar"));
  }
}

但是我还没有找到在 state 或 getter 中使用它的方法,因为他们无权访问this.

于 2021-04-05T05:24:09.867 回答
1

i18n 模块默认不注入到 store 上下文中,“this”关键字也无法访问该模块。

将翻译文件中的键保存为存储中的值甚至使用对象的 id 作为相同的翻译键,然后在组件中使用 $t 函数进行翻译不是更好的方法吗?

像下面这样

store.js

const state = {
   sortMethods: [
        {
           id: “airline”, 
           key_name: “airline”
        }
   ]
}

然后在你的 component.vue 中的 select 标签中:

<option v-for=“method in $store.state.sortMethods” :key=“method.id”&gt; {{$t(method.key_name)}}</option>

这将为您提供来自商店的翻译列表。不需要直接翻译。

您可以使用 id、键,甚至名称,在您的 lang 文件中始终使用相同的翻译键。

于 2020-12-30T00:38:30.157 回答