Vuex中dispatch和Commit的区别

官方解释

Commit

commit(type: string, payload?: any, options?: Object)
commit(mutation: Object, options?: Object)

提交 mutation。options 里可以有 root: true,它允许在命名空间模块里提交根的 mutation。

dispatch

dispatch(type: string, payload?: any, options?: Object): Promise<any>
dispatch(action: Object, options?: Object): Promise<any>

分发 action。options 里可以有 root: true,它允许在命名空间模块里分发根的 action。返回一个解析所有被触发的 action 处理器的 Promise。

理解

this.$store.dispatch 分发 actions-> 调用 mutations>改变 states

Vuex 中 dispatch()和 commit()的异同

  • 相同点

    都可以修改 state,并且也会触发视图的更新

  • 不同点

    commit 调用的是 vuex 中 mutation 里的方法,存在同步限制;而 dispatch 调用的数 vuex 中 action 里的方法,action 中可以调用 mutation 中的函数,也可执行异步操作

commit:同步操作

// 存储
this.$store.commit('chgval',name);
// 取值
this.$store.state.chgval;

dispatch:异步操作

// 存储
this.$store.dispatch('listdata',name);
// 取值
this.$store.getters.listdata;

猜你喜欢

转载自blog.csdn.net/H_jrqn/article/details/127382132