Vuex-Action

Action 相似於 mutation,不一樣在於:javascript

  • Action 提交的是 mutation,而不是直接變動狀態。
  • Action 能夠包含任意異步操做。

讓咱們來註冊一個簡單的 action:vue

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 實例自己了。java

實踐中,咱們會常常用到 ES2015 的 參數解構 來簡化代碼(特別是咱們須要調用 commit 不少次的時候):git

actions: {
  increment ({ commit }) {
    commit('increment')
  }
}

分發 Action

Action 經過 store.dispatch 方法觸發:es6

store.dispatch('increment')github

乍一眼看上去感受畫蛇添足,咱們直接分發 mutation 豈不更方便?實際上並不是如此,還記得 mutation 必須同步執行這個限制麼?Action 就不受約束!咱們能夠在 action 內部執行異步操做:vuex

actions: {
  incrementAsync ({ commit }) {
    setTimeout(() => {
      commit('increment')
    }, 1000)
  }
}

Actions 支持一樣的載荷方式和對象方式進行分發:異步

// 以載荷形式分發
store.dispatch('incrementAsync', {
  amount: 10
})

// 以對象形式分發
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

來看一個更加實際的購物車示例,涉及到調用異步 API 和分發多重 mutation函數

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)
    )
  }
}


//不習慣看es6語法的能夠看下面
actions: {
    checkout: function checkout(context, products) {
      var commit = context.commit,
      var state = context.state;

      // 把當前購物車的物品備份起來
      var savedCartItems = [].concat(_toConsumableArray(state.cart.added));
      // 發出結帳請求,而後樂觀地清空購物車
      commit(types.CHECKOUT_REQUEST);
      // 購物 API 接受一個成功回調和一個失敗回調
      shop.buyProducts(products,
      // 成功操做
      function () {
        return commit(types.CHECKOUT_SUCCESS);
      },
      // 失敗操做
      function () {
        return commit(types.CHECKOUT_FAILURE, savedCartItems);
      });
    }
  }

注意咱們正在進行一系列的異步操做,而且經過提交 mutation 來記錄 action 產生的反作用(即狀態變動)。this

在組件中分發 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` 也支持載荷:
      'incrementBy' // 將 `this.incrementBy(amount)` 映射爲 `this.$store.dispatch('incrementBy', amount)`
    ]),
    ...mapActions({
      add: 'increment' // 將 `this.add()` 映射爲 `this.$store.dispatch('increment')`
    })
  }
}
本站公眾號
   歡迎關注本站公眾號,獲取更多信息