Action 相似於 mutation,不一樣在於:vue
讓咱們來註冊一個簡單的 action:git
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 實例自己了。es6
實踐中,咱們會常常用到 ES2015 的 參數解構 來簡化代碼(特別是咱們須要調用 commit
不少次的時候):github
actions: { increment ({ commit }) { commit('increment') } }
Action 經過 store.dispatch
方法觸發: vuex
store.dispatch('increment')
乍一眼看上去感受畫蛇添足,咱們直接分發 mutation 豈不更方便?實際上並不是如此,還記得 mutation 必須同步執行這個限制麼?Action 就不受約束!咱們能夠在 action 內部執行異步操做:api
actions: { incrementAsync ({ commit }) { setTimeout(() => { commit('increment') }, 1000) } }
Actions 支持一樣的載荷方式和對象方式進行分發:cookie
// 以載荷形式分發 store.dispatch('incrementAsync', { amount: 10 }) // 以對象形式分發 store.dispatch({ type: 'incrementAsync', amount: 10 })
你在組件中使用 this.$store.dispatch('xxx')
分發 action,或者使用 mapActions
輔助函數將組件的 methods 映射爲 store.dispatch
調用(須要先在根節點注入 store
):session
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')` }) } }
Action 一般是異步的,那麼如何知道 action 何時結束呢?更重要的是,咱們如何才能組合多個 action,以處理更加複雜的異步流程?ecmascript
首先,你須要明白 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,咱們能夠以下組合 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 纔會執行
運用舉例
login.vue
login() { this.error = ""; if (!this.username) { this.error = "請輸入用戶名!"; return; } if (!this.passwd) { this.error = "請輸入密碼!"; return; } var self = this; this.$store .dispatch("doLogin", { username: this.username, passwd: this.passwd }) .then(resp => { this.$cookie.set("session_id", resp.data.session_id, 1); //有效期1天 this.$cookie.set("username", resp.data.username, 1); //有效期1天 self.$store.commit("SAVE_AUTHENTICATION", resp.data); self.$router.push({ path: "/index" }); }); }
/store/auth.js
import auth from "../../api/auth"; const VueCookie = require('vue-cookie') const user = { state: { username: "", // 用戶名 session_id: "", }, mutations: { SAVE_AUTHENTICATION(state, auth) { state.session_id = auth.session_id; state.username = auth.username; }, }, actions: { doLogin({ commit }, user) { var self = this; return new Promise((resolve, reject) => { auth .login(user) .then(resp => { if (resp.status != 200) { reject(resp.msg || "登陸錯誤"); } else { resolve(resp); } }) .catch(resp => { console.error(resp); reject("登陸錯誤"); }); }); } }, getters: { username: state => { if(!state.username){ state.username = VueCookie.get('username') } return state.username } } }; export default user;