[英]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.