【问题标题】:Vuex: How to store the result of a getter in the state?Vuex:如何将getter的结果存储在状态中?
【发布时间】:2018-12-16 21:23:56
【问题描述】:

我的 Vuex.Store 出现问题:

我想使用两个状态条目作为带有 getter 的搜索条件(state.array 和 state.selected)来获取一个对象(getter.getRecipe)。然后我想将该结果存储在我的状态(state.recipe)中,以便能够在组件中更新它(即,根据客户端操作更改配方对象的一个​​键)。 但是,我不知道如何在我的状态下存储 getter 的结果(“this.getters.getRecipe”不起作用......)。 对提示很有帮助。非常感谢。

//store.js (vuex store)

export const store = new Vuex.Store({
state: {
   array: [recipe1, recipe2],
   selected: 0,
   recipe: this.getters.getRecipe()
 },
getters: {
   getRecipe: (state) => {
    return state.array[state.selected]
   }
 }
})

【问题讨论】:

  • 你不觉得这是违反直觉的。你的状态就是你的状态,你的吸气剂就是吸气剂。
  • 相反,您应该使用 getters 之类的 getter,并从您的状态获取数据
  • getter 像计算属性一样被缓存。所以你不需要额外的状态属性。你可以只使用getter getRecipe
  • @Derek 感谢您的快速回复。关键是,我需要一个结果(即对当前状态的操作),然后以某种方式将该结果保存在状态中。我怎么能这样做?
  • 只要 getter 依赖的属性发生变化,getter 就会自动更新。因此,在您的情况下,state.arraystate.selected 更改将导致 getter 更新。

标签: javascript vue.js vuex


【解决方案1】:

您应该使用Method style getters with arguments:

您还可以通过返回函数将参数传递给 getter。这在您想查询存储中的数组时特别有用:

一个基本的例子:

getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}

然后,使用示例:

store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

或者,从组件内部:

this.$store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

通过这种方式,您可以确保您的状态仍然是一个纯数据结构,遵循由通量模式规定的单向数据流。

【讨论】:

  • 非常感谢德里克。你帮助我清楚地表明我的方法违背了一些原则。从这里自己,我可以继续,因为我的例子当然更复杂。继续后可能会再次发布更具体的问题。我的关键问题不是获取数据,而是最初基于一个组件(state.selected)中的客户选择计算数据,然后通过交互让客户有机会再次操作该数据(当然存储在存储中)。 THX 男人!
猜你喜欢
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
  • 2019-03-21
  • 2020-06-03
  • 2019-08-06
  • 2021-06-01
  • 2019-10-18
相关资源
最近更新 更多