美文网首页
34-Vuex-actions

34-Vuex-actions

作者: 早起的鸟儿 | 来源:发表于2019-10-31 08:53 被阅读0次

    Action 类似于 mutation,不同在于:

    Action 提交的是 mutation,而不是直接变更状态(state)。
    Action 可以包含任意异步操作。

    在index.js中:

    ...
    const state = {
        count:1
    }
    const mutations = {   //管理事件类型
        add(state){
            state.count += 1
        },
        reduce(state,step){
            state.count -= step;
            console.log(2)
        }
    }
    const actions = {  //提交事件,提mutations里的事件,可以在这里进行逻辑判断...操作
        add({commit}){   //简化版写法
          commit("add")  //对应mutations里边的事件名
        },
        reduce(context,step){  //完整写法
          console.log(1)
          context.commit("reduce",step)
       }
    }
    //当我点击➖时候,先执行actions,打印1;再执行mutations,打印2
    export default new Vuex.Store({
        state,
        mutations,
        actions
    })
    

    Action 函数接受一个与 store 实例具有相同方法和属性的 context 对象,因此你可以调用 context.commit 提交一个 mutation,或者通过 context.statecontext.getters 来获取 state 和 getters。当我们在之后介绍到 Modules 时,你就知道 context 对象为什么不是 store 实例本身了。

    在任意组件内:

    <div>{{count}}</div>
    <button @click="add()">+</button>
    <button @click="reduce()">-</button>
    
    computed:mapState(["count"]),
    methods:{
       reduce(){
          this.$store.dispatch("reduce",2);
       },
       add(){
           this.$store.dispatch("add")
       },
       // ...mapActions(['add','reduce'])
    }
    

    你在组件中使用 this.$store.dispatch('xxx') 分发 action,或者使用 mapActions 辅助函数将组件的 methods 映射为 store.dispatch 调用。

    到此为止,上述的写法和直接使用mutations是一样效果,那为什么还需要actions呢?可以参考另一篇文章https://www.jianshu.com/writer#/notebooks/38257501/notes/51022648

    image.png

    组件中想要修改state的数据,通过dispatch调用actions,在acitons中通过commit调用mutations来修改数据
    如果没有异步操作或者是批量处理可以直接通过commit调用mutations.

    相关文章

      网友评论

          本文标题:34-Vuex-actions

          本文链接:https://www.haomeiwen.com/subject/ogwcmctx.html