vuex学习六----actions

来源:互联网 发布:巴黎住宿攻略 知乎 编辑:程序博客网 时间:2024/06/13 11:43

1:Actions

Action类似于mutation。不同在于:

  1. Action提交的是mutation,而不是直接变更状态;
  2. 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才会执行;

原创粉丝点击