vuex学习六----actions
来源:互联网 发布:巴黎住宿攻略 知乎 编辑:程序博客网 时间:2024/06/13 11:43
1:Actions
Action类似于mutation。不同在于:
- Action提交的是mutation,而不是直接变更状态;
- Action可以包含任意异步操作;
const store=new Vuex.Store({ state:{ count:0 }, mutation:{ increment(state){ state.count++ } }, actons:{ increment(count){ context.commit('increment') } }})
Action函数接收一个与store实例具有相同方法跟属性的context对象,因此你可以调用context.commit提交一个mutation,或者通过context.state根context.getters来获取state跟getters。context对象不是store实例本身;
ES2015的参数解构来简化代码(☚待研究☛)
actions:{ increment({commit}){ commit('increment') }}
2:分发Action
Action通过store.dispatch方法触发:
store.dispatch('increment')
action内部执行异步操作
actions:{ increment({commit}){ setTimeout( ()=>{commit('increment')},1000 ) }}
Action支持同样的载荷方式和对象方式进行并发:
//载荷形式分发store.dispatch('increment',{amount"10})//以对象形式分发store.dispatch({ type:'incrementAsync', amount:10})
实际购物车实例,涉及到调用异步API跟分发多重mutations
actions:{ checkout({ commit , state },products){ //把当前购物车的物品备份起来 const savedCartItems=[...state.cart.added] } //发出结账请求,然后乐观的清空购物车 commit(types.CHECKOUT_REQUEST) //购物API接受一个成功回调和一个失败回调 shop.buyProducts( products, //成功操作 ()=>commit(types.CHECK_SUCCESS), //失败操作 ()=>commit(types.CHECK_FAILURE, savedCartItems), )}
3:在组建中分发Action
在组建中使用this.$store.dispatch(‘XXX’)分发action,或者使用mapActions辅助函数将组件中的methods映射为store.dispatch调用(需要在根节点注入store)
import { mapActions } from 'vuex'export default{ methods:{ ...mapActions([//映射this.increment()为this.$store.dispatch('increment') 'increment' ]),//映射this.add()为this.$store.dispatch('increment') ...mapActions([ add:'cincrement' ]) }}
4:组合 Actions
store.dispatch可以处理被触发的action的回调函数返回的Promise,并且store.dispatch仍旧返回Promise:
actions:{ actionA({ commit}){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ commit('someMutation') },1000) }) }}
现在你可以:
store.dispatch('actionA').then()=>{}
在另外一个action中也可以:
actions:{ actionB({ dispatch,commit }){ return dispatch('actionA').then(()=>{ commit('someOtherMutation') }) }}
最后我们利用JS新特性,async/await组合action
//假设getData(),getOtherData()返回的是Promiseactions:{//async 表示这是一个async函数,await只能用在这个函数里面。 async actionA({commit}){ commit('gotData',swait getData()) }, async actionA({commit}){ //等待action完成,await 后面跟着的应该是一个promise对象 await dispatch('actionA') commit('gotOtherData',await getOeherData()) }}
一个store.dispatch在不同模块中可以触发多个action函数。在这种情况下,只有当所有触发函数完成后,返回的Promise才会执行;
阅读全文
0 0
- vuex学习六----actions
- Vuex中mutations和actions的区别
- vuex学习
- 学习vuex
- vuex所有核心概念完整解析State Getters Mutations Actions
- Vuex 学习总结
- Vuex学习笔记
- vuex学习实践笔记
- vuex的入门学习
- Vuex学习笔记
- VUEX学习与实践
- Vuex 学习总结
- vuex学习实践笔记
- vuex学习实践笔记
- vuex学习总结
- vuex学习笔记
- vuex学习一
- vuex学习二
- Linux 安装 Eclipse
- lambda函数
- 从mysql中将数据表复制给hbase
- OSG学习:计算纹理坐标
- 算法2:树的带权路径长度(创新工场)
- vuex学习六----actions
- android自定义跑马灯
- Xtrabackup2.3.6 安装
- 博客积分
- linux shell编程
- HDU 4765 Tsp 2013长春网络赛G题 DP
- Spring:IoC 用法(八、<bean>用法)
- java面试 用过哪些java2e框架,优缺点。
- JDBC(4)—Preparedstatement