簡體   English   中英

Vuex:如何在狀態中存儲獲取器的結果?

[英]Vuex: How to store the result of a getter in the state?

我的Vuex.Store有問題:

我想使用兩個狀態條目和一個帶有吸氣劑的搜索條件(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]
   }
 }
})

相反,您應該使用帶有參數的Method樣式獲取器

您還可以通過返回函數將參數傳遞給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 }

這樣,您可以確保狀態保持純數據結構,並遵循通量模式提出的一種數據流方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM