vuex中store.commit和store.dispatch的区别及使用方法

2023-01-10 10:37:10

目录store.commit和store.dispatch的区别及使用规范的使用方式主要区别this.$store.dispatch()与this.$store.commit()总结store.c...

目录
store.commit和store.dispatch的区别及使用
规范的使用方式
主要区别
this.$store.dispatch() 与 this.$store.commit()
总结

stjavascriptore.commit和store.dispatch的区别及使用

代码示例:

this.$store.commit('loginStatus', 1);

this.$store.dispatch('isLogin', true);

规范的使用方式

// 以载荷形式
store.commit('increment',{
 amount:python 10  //这是额外的参数
})

// 或者使用对象风格的提交方式
store.commit({
 type: 'increment',
 amount: 10  //这是额外的参数
})

主要区别

dispatch:含有异步操作,数据提交至 actions ,可用于向后台提交数据

this.$store.dispatch('isLogin', true);

commit:同步操作,数据提交至 mutations ,可用于读取用户信息写到缓存里

this.$store.commit('loginStatus', 1);

this.$store.dispatch() 与 this.$store.commit()

传值给vuex的mutation改变state

commit: 同步操作

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

dispatch: 异步操作

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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。