Vuex-Action

Action 相似于 mutation,不一样在于:vue

  • Action 提交的是 mutation,而不是直接变动状态。
  • Action 能够包含任意异步操做。

让咱们来注册一个简单的 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

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

在组件中分发 Action

你在组件中使用 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 何时结束呢?更重要的是,咱们如何才能组合多个 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;
本站公众号
   欢迎关注本站公众号,获取更多信息