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。

打完收工!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章