actions

发布时间 2023-10-13 11:28:56作者: 嘎嘎鸭2

actions:处理异步操作

需求:一秒钟之后,修改 state 的 count 成 666

说明:mutations 必须是同步的(便于监测数据变化,记录调试)

 

actions 使用步骤:

1. 提供 actions 方法:

(actions 本质上不是直接修改 state 的数据,因为要修改 state 必须要经过 mutations,所以就算想要处理异步,也是在 actions 中把异步处理完了,然后在里面去用 mutations,actions 相当于帮我们把异步给包装处理掉了)

actions : {

      setAsyncCount (context, num) {                             // context:上下文,此处未分模块,可以理解为 store 仓库;num:参数

            setTimeout ( () => {                                          // 这里是 setTimeout 模拟异步,以后大部分场景是发请求(发请求也是异步)

                  context.commit ( ' changeCount ' ,  num)   // 提交 mutations :context.commit ( ' mutations 中方法名字 ' ,  参数 )

            } ,  1000)

      }

}

2. 页面中 dispatch 调用:

   this.$store.dispatch ( ' setAsyncCount ' ,  200)