Vuex Actions 异步修改状态

Action 类似于 mutation,不同在于:

Action 提交的是 mutation,而不是直接变更状态。

Action 可以包含任意异步操作。

注册一个简单的 action:

Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此可以调用 context.commit 提交一个 mutation,或者通过 context.state 和 context.getters 来获取 state 和 getters。

分发 Action

Action 通过 store.dispatch 方法触发:

mutation 必须同步执行,Action 就不受约束, 在 action 内部执行异步操作:

在addAction里使用setTimeOut进行延迟执行

Actions 支持同样的载荷方式和对象方式进行分发:

接收载荷:

mapActions辅助函数

在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions辅助函数将组件的 methods 映射为 store.dispatch 调用(需要先在根节点注入 store):

组合 Action

待续。。。。

你可能感兴趣的:(Vuex Actions 异步修改状态)