Vuex:store.commit和store.dispatch的区别

一、来源

store.commit()

  • mutation注册了一个变更状态的事件后,需要调用 store.commit()来进行状态变更
  • 例如:store.commit('aaa')

store.dispatch()

  • 是dispatch是触发action的一种方法
  • 例如:store.dispatch('aaa')

二、共同点:

在更改状态、触发更改状态时都可以以载荷方式和对象方式进行分发.

store.commit()

store.commit('increment', {
  amount: 10
})

store.commit({
  type: 'increment',
  amount: 10
})

store.dispatch()

store.dispatch('incrementAsync', {
  amount: 10
})

// 以对象形式分发
store.dispatch({
  type: 'incrementAsync',
  amount: 10
})

三、区别

为了保证数据的状态稳定,可控,mutation“必须”是同步的,即:

  • commit:同步操作
  • dispatch:可以是异步操作,数据提交至 actions ,可用于向后台提交数据
发布了292 篇原创文章 · 获赞 48 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/jbj6568839z/article/details/105291352