異步處理需要在 倉庫的actions中定義
Action 類似于 mutation,不同在于:
· Action 提交的是 mutation,而不是直接變更狀態。
· Action 可以包含任意異步操作。
我們可以在action中發送異步請求,成功后觸發mutation 將結果傳入,在mutation賦值給state
const store = new Vuex.Store({
state: {
items: [] // 定義一個公共的購物車數據
},
mutations: {
// 定義mutation來修改state
INIT_ITEMS(state, items){
state.items = items
}
},
actions: {
// action可以發送異步請求,得到數據后commit mutation將請求結果傳入
FETCH_ITEMS({commit}, params = {}){
// 調用封裝好的 接口函數
fetchItem(params).then(res => {
if(res.data.code === 200) {
commit('INIT_ITEMS', res.data.data)
}
})
}
}
})