vue---操作状态

VUE更改VUEX状态:简单示例代码:

复制代码
import Vue from 'vue';  
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({  
  state: {  
    count: 0  
  },  
  mutations: {  
    increment (state) {  
      state.count++;  
    },  
    decrement (state) {  
      state.count--;  
    }  
  },  
  actions: {  
    increment ({ commit }) {  
      commit('increment');  
    },  
    decrement ({ commit }) {  
      commit('decrement');  
    }  
  }  
});
复制代码

在该状态管理中,如果直接想要操作改变状态,可以使用 this.$store.commit 来调用 mutations,例如:

this.$store.commit('increment'); 
this.$store.commit('decrement');

此外也可以使用 this.$store.dispatch 来调用 actions 来 操作 mutations 改变状态,例如:

this.$store.dispatch('increment');
this.$store.dispatch('decrement');

那么 this.$store.commit 和 this.$store.dispatch 有什么区别:

commit方法:用于调用 Vuex store 中的 mutations。mutations 是同步事务,用于直接更改状态。当你在组件中需要直接更改状态时,可以使用 commit 方法来调用相应的 mutation。

dispatch 方法用于调用 Vuex store 中的 actions。actions 是用于处理异步操作或执行多个 mutations 的函数。与 mutations 不同,actions 不直接改变状态,而是通过调用 mutations 来改变状态。当你在组件中需要执行异步操作或需要执行多个 mutations 时,可以使用 dispatch 方法来调用相应的 action。

例如:通常会在 actions 里面进行异步操作后改变状态,此时就需要使用 dispatch 来驱动:

区别:

this.$store.commit 直接调用 mutations 来同步地改变状态。

this.$store.dispatch 调用 actions 来处理异步操作或执行多个 mutations。actions 最终还是会通过调用 mutations 来改变状态。

如果你需要执行的操作是同步的并且只需要改变状态,那么使用 commit。如果你需要执行异步操作或需要执行一系列操作,那么使用 dispatch。

打完收工!

posted @   帅到要去报警  阅读(17)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
历史上的今天:
2021-12-15 uniapp---组件以及icon图标
2018-12-15 php---进行签名验证
2018-12-15 php---进行RSA进行非对称加密
2018-12-15 python---使用md5加密
2018-12-15 python---不支持中文注释解决办法
2018-12-15 python---修改编辑器的配色和字体大小
2018-12-15 python---使用pycharm运行py文件
点击右上角即可分享
微信分享提示