我對找到一個我認爲對於像Vuex這樣的東西很常見的用例的例子感到沮喪。Vuex在異步狀態改變後執行函數
我在商店調度異步操作以通過API填充它。一旦這個商店被填充,我需要執行某些操作。
我遇到的每個Vuex例子似乎只是處理對UI的直接更新。但幾乎在每種情況下,我都需要執行基於關鍵組件的操作。
state: {
// initial state values are all falsey
id: false,
name: false,
},
getters: {
getItem: (state) => {
return state;
},
},
actions: {
setItem({commit}) {
// async call to get and then commit the state
}
}
以上是商品店的相關片段一個很簡單的例子,那裏電話調度的動作通常從這裏就不詳述了一個組件調用。以下是我正在觀看要填充項目的組件。
watch: {
item: function (newItem) {
this.doSomethingWith(newItem); // this never runs
}
},
computed: {
...mapGetters({
item: 'getItem',
}),
},
mounted() {
console.log(this.item); // I get an observer of the item object
// none of items state properties are defined during mounted
},
methods: {
doSomethingWith(item) {
// I want to do something here with the set item!!
}
}
我期望項目狀態不會在掛載時設置,因爲它是對外部api的異步調用。然而我所期望的是,當它最終被填充時,觀察者會捕捉到它並允許我在組件內部運行後續操作。但是手錶不會發生火災。
那麼,如何在組件和運行操作中像這樣跟蹤這些變化取決於它們的新狀態?
您已將'item'映射到'getItem' getter,但您的示例具有'getUnit' getter。 – thanksd
這是一個錯字 - 我從現有的應用程序複製代碼並試圖使其更一般化。我已經更新了這個問題。 –