1vuex中action和mutations (this.$store.dispatch和this.$store.commit)的区别(都是调用vuex中的方法。一个异步一个同步)

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

commit:同步操作,写法:this.$store.commit('mutations方法名',值)

action:

1、用于通过提交mutation改变数据

2、会默认将自身封装为一个Promise

3、可以包含任意的异步操作

mutations:

1、通过提交commit改变数据

2、只是一个单纯的函数

3、不要使用异步操作,异步操作会导致变量不能追踪。也就是说,用action中的函数调用mutations中的函数,进行异步操作state中的数据

2 用法

dispatch: 含有异步操作

存储:

this.$store.dispatch('initUserInfo',friend);

取值:

this.$store.getters.userInfo;

commit:同步操作

存储:

this.$store.commit('initUserInfo',friend);

取值:

this.$store.state.userInfo;

 

3 实例:

1、login.vue 

 

2、user.js

3、login.js

 

 

Logo

前往低代码交流专区

更多推荐