vuex中dispatch与commit的使用和区别

在这里插入图片描述

一开始接触Vuex的时候,被dispatch和commit搞得很是头疼,不知道什么时候需要使用dispacth派发action,什么时可以直接commit。索性今天借着项目里真实用到的2种情况来说一下。

1.dispatch和commit的作用和区别

相同点:二者最终都是用来提交mutation来更改state的值的
不同点:dispacth用于异步操作修改state,commit用于同步操作来修改state
说到这里,就开水抓狂了,到底什么是异步修改state,什么是同步修改state

别急,先看案例

2.异步修改state

先看一个场景,state里面有一个默认的用户信息userInfo,我们定义一个mutation和一个action用于修改它

const state={
    
    
 userInfo{
    
    
   name:"Tom",
   age:"13"
 }
}


const mutations={
    
    
 //更新用户信息的mutation
   SET_USER_INFO:(state,newUserInfo)=>{
    
    
     state.userInfo=newUserInfo
  }
}


const actions={
    
    
    //用于提交mutation的action
    changeUserInfo({
     
     commit},data){
    
    
        commit('SET_USER_INFO',data)
    }

}



在getters中拿到最新的userInfo

const getters = {
    
    
  userInfo: state => state.userInfo,

}
export default getters

然后,在user.vue这个文件中,我们来异步更新state中的userInfo,如何异步更新呢?就是我们要更新的值是通过调用后端接口拿来的。

import  {
    
    getUserInfo} from "api"
export default {
    
    
  name: 'User',
  computed:{
    
    
    userInfo(){
    
    
     return this.$store.getters.userInfo; //第三步:使用getters获取最新的userInfo
    }
  },
  
  methods:{
    
    
      
      reqUserInfo(){
    
    
         //第一步:调用后端接口,获取用户信息
          getUserInfo()
           .then((res)=>{
    
    
              let data=res.data.userInfo;
              //第二步:将异步拿到的用户信息,使用disptch派发action,action提交mutation更新state的值
              this.$store.dispatch('changeUserInfo',data) 
           })
           
           .catch((err)=>{
    
    
              console.log(err)
           })
           
      }
  }	
    	
}

看到这里,还是没看出区别是不是,别急,继续看。

3.同步修改state

同样的代码,我们同步修改,何为同步,就是我们要更新的值,不是通过调用后端接口拿到的

export default {
    
    
  name: 'User',
  computed:{
    
    
    userInfo(){
    
    
     return this.$store.state.userInfo; //第三步:直接拿到state中的userInfo
    }
  },
  
  methods:{
    
    
      //第一步:生成用户信息
      const data={
    
    
         name:"Tom",
         age:"13"
      }
      
      //第二步:使用commit提交mutation来更新state
      this.$store.commit('SET_USER_INFO',data)
      
    
  }	
    	
}

相信大家也看出区别了,本质上,最终都是使用commit提交mutation来修改state,异步和同步的区别在于异步更新必须通过派发action来更新mutation,而同步更新可以直接提交mutation来更新state.

当然,同步更新也可以使用派发action的方式,因为vue官方推荐这种做法
但是,异步更新只能使用户派发action的方式

4.总结一下

commit 和dispatch的区别在于commit是提交mutatious的同步操作,dispatch是分发actions的异步操作
action不能直接修改state值
action 必须通过提交mutation来更新state
只有mutation才能更新state

this.$store.dispatch() :含有异步操作,例如向后台提交数据,写法:this.$store.dispatch(‘action方法名’,)
this.$store.commit():同步操作,,写法:this.$store.commit(‘mutations方法名’,)

commit: 同步操作

存储 this.$store.commit('changeValue',name)
取值 this.$store.state.changeValue


dispatch: 异步操作

存储 this.$store.dispatch('getlists',name)
取值 this.$store.getters.getlists

作者:清风夜半
链接:原文作者
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自blog.csdn.net/m0_66504310/article/details/128866202