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

 更新时间:2023年01月10日 10:12:49   作者:longzhoufeng  
这篇文章主要介绍了vuex中store.commit和store.dispatch的区别及使用方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

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

代码示例:

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

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

规范的使用方式

// 以载荷形式
store.commit('increment',{
  amount: 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

总结

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

相关文章

最新评论