【问题标题】:nuxt : access globals variables stored in the vuex storenuxt :访问存储在 vuex 存储中的全局变量
【发布时间】:2019-05-02 12:10:44
【问题描述】:

在我的 NUXT 应用程序中,我必须为我的所有组件共享一个全局数组。 例如,这个数组包含星期的标签:

export const state = () => ({
  days: [
      { code: '1', label: 'Lundi' },
      { code: '2', label: 'Mardi' },
      { code: '3', label: 'Mercredi' },
      ...
  ]
})

export const getters = {
  getDayLabel (state, dayCode) {
    return state.days[dayCode]
  },
}

在我的组件中,我必须显示一天的标签。为此,我在组件的模板中写了:

{{$store.getters['getDayLabel'](dayCode)}}

但是,我有这个错误:

app.js:262 TypeError: _vm.$store.getters.getDayLabel 不是函数

我读过一些主题,getter 函数不应该有参数?有没有更好的解决方案?

埃里克。

【问题讨论】:

    标签: parameters vuejs2 vuex getter nuxt.js


    【解决方案1】:

    你不需要在 store 中为 getter 指定新参数

    例如一个 getter,你只用索引来检索信息:

     export const getters = {
        getDayLabel: state => index => state.days[index]
    }
    

    在您的模板中: {{$store.getters['getDayLabel'](1).label }} --> output = Mardi

    如果你真的想用代码搜索你可以使用过滤功能:

      getDayLabel: state => {
        return dayCode => state.days.filter(c => {
          return c.code === dayCode
        })
      }
    

    在您的模板中: {{$store.getters['getDayLabel'](2)[0].label }} --> output = Mardi

    更多信息在这里Github issue

    我不知道这是否是一个好习惯,因为我以前从未这样使用过,我总是直接在组件中对数据进行过滤。

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 2021-12-07
      • 2019-05-26
      • 2021-06-17
      • 2020-05-20
      • 2018-11-10
      • 2021-07-15
      • 1970-01-01
      • 2021-09-18
      相关资源
      最近更新 更多