什么时候才用到action的异步方法呢
如题,我还以为是大量的数据改变才取用呢,不管如何,邢老师具体给个例子说明一下什么情况采用action这样我比较好理解
正在回答 回答被采纳积分+1
同学你好,不应该是dispatch和commit的比较。因为dispatch执行的是actions,actions中函数可以是异步执行,commit提交的是mutations,里面函数只能是同步执行 。应该是看actions中使用异步提交commit的区别。
老师只是举个例子,但是测试结果和直接使用commit提交是一样的。官网中说的异步主要涉及到执行顺序问题。例如有两个异步操作,第二个异步操作的条件依赖第一个异步操作的结果。第一个异步操作执行了num++ ,第二个异步操作会先判断当前num的值,例如if(num === 4) { 执行代码} else {执行代码},希望按照顺序执行,执行完第一个,用第一个结果再执行第二个。
但是实际使用中,例如接口访问,往往是不能确定执行完成的时间的,有时候第一个异步操作还没有拿到数据,第二个异步操作就执行了,无法使用数据,结果就会有误。所以一般actions中会结合promise实现异步操作。官网中有举例子
https://vuex.vuejs.org/zh/guide/actions.html
目前了解一下即可。祝学习愉快!
同学你好,可以参考下面的例子:比如先提交add,两秒之后提交reduce。在actions中异步提交:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | <!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < title >Document</ title > </ head > < body > < div id = "app" > < p @ click = "changeNum()" >{{num}}</ p > </ div > < script src = "js/vue.js" ></ script > < script src = "https://unpkg.com/vuex@3.5.1/dist/vuex.js" ></ script > < script > const store = new Vuex.Store({ state: { count: 2 }, mutations: { add(state) { state.count += 3; }, reduce(state) { state.count--; } }, actions: { changeNum(ctx) { ctx.commit('add'); setTimeout(() => { ctx.commit('reduce'); }, 2000); } } }) new Vue({ el: '#app', data() { return { num: this.$store.state.count } }, store: store, methods: { changeNum() { var _this = this; this.$store.dispatch('changeNum'); setTimeout(() => { _this.num = _this.$store.state.count; }, 2000); } } }) </ script > </ body > </ html > |
自己测试下,祝学习愉快!
- 参与学习 人
- 提交作业 239 份
- 解答问题 10739 个
本阶段带你深入前端开发的肌理,通过ES6基础知识和前端主流高级框架的学习,助你快速构建企业级移动webAPP应用,进入职场的终极battle
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧