Vuex Action vs Mutations

前端 未结 13 1107
囚心锁ツ
囚心锁ツ 2020-12-02 04:37

In Vuex, what is the logic of having both \"actions\" and \"mutations?\"

I understand the logic of components not being able to modify state (which seems smart), but

13条回答
  •  没有蜡笔的小新
    2020-12-02 05:20

    It might seem unnecessary to have an extra layer of actions just to call the mutations, for example:

    const actions = {
      logout: ({ commit }) => {
        commit("setToken", null);
      }
    };
    
    const mutations = {
      setToken: (state, token) => {
        state.token = token;
      }
    };
    

    So if calling actions calls logout, why not call the mutation itself?

    The entire idea of an action is to call multiple mutations from inside one action or make an Ajax request or any kind of asynchronous logic you can imagine.

    We might eventually have actions that make multiple network requests and eventually call many different mutations.

    So we try to stuff as much complexity from our Vuex.Store() as possible in our actions and this leaves our mutations, state and getters cleaner and straightforward and falls in line with the kind of modularity that makes libraries like Vue and React popular.

提交回复
热议问题