nuxt :访问存储在 vuex 存储中的全局变量

nuxt : access globals variables stored in the vuex store

在我的 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 is not a function

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

埃里克

您不需要在商店中为 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

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