vue在服務端異步調用API獲取的數據會超出服務器渲染生命週期。
解決方案用上vuex狀態管理
Actions方法vue
Action 相似於 mutation,不一樣在於:vuex
**Action 提交的是 mutation,而不是直接變動狀態。
Action 能夠包含任意異步操做。
讓咱們來註冊一個簡單的 action:**服務器
const store = new Vuex.Store({ state: { count: 0 }, mutations: { increment (state) { state.count++ } }, actions: { increment (context) { context.commit('increment') } } })
Action 函數接受一個與 store 實例具備相同方法和屬性的 context 對象,所以你能夠調用 context.commit 提交一個 mutation,或者經過 context.state 和 context.getters 來獲取 state 和 getters。當咱們在以後介紹到 Modules 時,你就知道 context 對象爲何不是 store 實例自己了。異步
實踐中,咱們會常常會用到 ES2015 的 參數解構 來簡化代碼(特別是咱們須要調用 commit 不少次的時候):async
actions: { increment ({ commit }) { commit('increment') } }
分發 Action函數
Action 經過 store.dispatch 方法觸發:this
store.dispatch('increment')
乍一眼看上去感受畫蛇添足,咱們直接分發 mutation 豈不更方便?實際上並不是如此,還記得 mutation 必須同步執行這個限制麼?Action 就不受約束!咱們能夠在 action 內部執行異步操做:spa
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }
Actions 支持一樣的載荷方式和對象方式進行分發:code
// 以載荷形式分發 store.dispatch('incrementAsync', { amount: 10 }) // 以對象形式分發 store.dispatch({ type: 'incrementAsync', amount: 10 })
來看一個更加實際的購物車示例,涉及到調用異步 API 和 分發多重 mutations:對象
actions: { checkout ({ commit, state }, products) { // 把當前購物車的物品備份起來 const savedCartItems = [...state.cart.added] // 發出結帳請求,而後樂觀地清空購物車 commit(types.CHECKOUT_REQUEST) // 購物 API 接受一個成功回調和一個失敗回調 shop.buyProducts( products, // 成功操做 () => commit(types.CHECKOUT_SUCCESS), // 失敗操做 () => commit(types.CHECKOUT_FAILURE, savedCartItems) ) } }
注意咱們正在進行一系列的異步操做,而且經過提交 mutation 來記錄 action 產生的反作用(即狀態變動)。
在組件中分發 Action
你在組件中使用 this.$store.dispatch('xxx') 分發 action,或者使用 mapActions 輔助函數將組件的 methods 映射爲 store.dispatch 調用(須要先在根節點注入 store):
import { mapActions } from 'vuex' export default { // ... methods: { ...mapActions([ 'increment' // 映射 this.increment() 爲 this.$store.dispatch('increment') ]), ...mapActions({ add: 'increment' // 映射 this.add() 爲 this.$store.dispatch('increment') }) } }
組合 Actions
Action 一般是異步的,那麼如何知道 action 何時結束呢?更重要的是,咱們如何才能組合多個 action,以處理更加複雜的異步流程?
首先,你須要明白 store.dispatch 能夠處理被觸發的action的回調函數返回的Promise,而且store.dispatch仍舊返回Promise:
actions: { actionA ({ commit }) { return new Promise((resolve, reject) => { setTimeout(() => { commit('someMutation') resolve() }, 1000) }) } }
如今你能夠:
store.dispatch('actionA').then(() => { // ... })
在另一個 action 中也能夠:
actions: { // ... actionB ({ dispatch, commit }) { return dispatch('actionA').then(() => { commit('someOtherMutation') }) } }
最後,若是咱們利用 async / await 這個 JavaScript 即將到來的新特性,咱們能夠像這樣組合 action:
// 假設 getData() 和 getOtherData() 返回的是 Promise actions: { async actionA ({ commit }) { commit('gotData', await getData()) }, async actionB ({ dispatch, commit }) { await dispatch('actionA') // 等待 actionA 完成 commit('gotOtherData', await getOtherData()) } }
一個 store.dispatch 在不一樣模塊中能夠觸發多個 action 函數。在這種狀況下,只有當全部觸發函數完成後,返回的 Promise 纔會執行。