【问题标题】:Using i18n-nuxt $t in Vuex store在 Vuex 商店中使用 i18n-nuxt $t
【发布时间】:2020-12-29 07:52:25
【问题描述】:

我的问题有点具体。我在这个项目中使用 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' },

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

【问题讨论】:

  • 你能提供你的商店文件的完整代码sn-p吗?

标签: vue.js internationalization vuex nuxt-i18n


【解决方案1】:

可以在带有this.$i18n.t 的突变和操作中使用t。例如:

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

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

【讨论】:

  • this.$i18n.te 也可以!您只需要小心并删除所有这些该死的$
【解决方案2】:

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

不是更好的办法是把翻译文件中的key作为值保存在store中,甚至使用对象的id作为同一个翻译key,然后在组件中使用$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”> {{$t(method.key_name)}}</option>

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

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

【讨论】:

    猜你喜欢
    • 2021-07-22
    • 1970-01-01
    • 2018-11-23
    • 2018-12-19
    • 2020-08-25
    • 2020-12-07
    • 2019-11-04
    • 1970-01-01
    • 2019-03-23
    相关资源
    最近更新 更多