vuex简单梳理4,actions的用法和其辅助函数

actions用来调用异步的方法,再通过触发Mutations来修改state

现在虽然在Mutations中调用异步方法也不会报错了,但是也要遵守vuex中的规则,也为日后维护的人员增加代码的可读性。

const state = {
    s:0,
}
const mutations = {
    SET_S(state,num){
        state.s = num;
    }

}
const actions = {
    sum({commit},params){//默认的参数commit,通过commit来调用定义在Mutations中的方法
        setTimeout(()=>{
            console.log(params.a-0,params.a)
            commit("SET_S",(params.a - 0 )+ (params.b - 0))
        },3000)
    },
  
}

组件中同dispatch调用actions中的方法

<div>
        <h3>actions</h3>
        <input type="text" ref="a">+
        <input type="text" ref="b">
        <input type="button" @click="$store.dispatch('sum',{a:$refs.a.value,b:$refs.b.value})"  value="=">//通过dispatch调用
        <input type="button" @click="sum({a:$refs.a.value,b:$refs.b.value})"  value="=">//辅助函数
        
        {{$store.state.s}}
      
    </div>

其辅助函数用法与之前类型

import {mapActions} from "vuex";
methods:{...mapActions(["sum",'test']),
                ...{
                    set(num){
                        this.$store.dispatch('test',num)
                        console.log(this.$store,'vuex状态')
                    }
                }
        }

这里多说一句,当我在实际项目中通过封装好的axios或者直接使用promise,在异步中再调用异步时就会 体会到actions的好处

vuex的梳理告一段落

posted @ 2020-09-08 14:00  忽闻河东狮子吼  阅读(605)  评论(0编辑  收藏  举报