在 Vuex 中, commitdispatch 都是用来触发一个 mutation 的方法。

commit 用于同步地提交一个 mutation,可以直接修改 state 中的值。例如:

mutations: {
  increment(state) {
    state.count++;
  }
}

store.commit('increment');

dispatch 用于异步地触发一个 mutation 或 action。它会返回一个 Promise,可以在异步操作完成后执行一些额外的操作。例如:

actions: {
  incrementAsync({ commit }) {
    return new Promise((resolve) => {
      setTimeout(() => {
        commit('increment');
        resolve();
      }, 1000);
    });
  }
}

store.dispatch('incrementAsync').then(() => {
  console.log('incrementAsync finished');
});
vuex commit 和dispatch

原文地址: https://www.cveoy.top/t/topic/66a 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录