因为mutation必须是同步函数,但是当我们需要异步的时候怎么办呢?这个时候就有了action,先看一下官网对Action的介绍:
Action 类似于 mutation,不同在于:
Action 提交的是 mutation,而不是直接变更状态。
Action 可以包含任意异步操作。
先看效果图:点击加一按钮,数字会延时1秒钟加一,点击减1按钮,延时1秒减一,点击加n按钮,对应的值加随机数

首先我们需要在store里的js加上如下代码:

组件中怎么使用呢?Action 通过 store.dispatch 方法触发:store.dispatch('increment')
或者通过映射:首先先引入mapActions :import { mapActions } from 'vuex',使用如下图:

所述内容如有错误感谢指正;如遇到问题,欢迎交流。
网友评论