Vuex - 仅将突变暴露给动作

Vuex - expose mutations only to actions

我想使用 Vuex 来存储有关我的客户端-服务器通信的状态,例如搜索逻辑:

// status is either synching|synched|error
state: { query:"", result:[], status:"synching" } 

我执行搜索动作。动作只能通过突变修改状态:

function search(context, query) {
    context.commit("query", query);
    context.commit("status", "synching");

    // some asynch logic here
    ...
        context.commit("result", result);
        context.commit("status", "synched");
    ...
}

但是,现在突变也暴露给了我的组件,它们现在能够使我的状态不一致。是否可以隐藏组件的突变?

动作可以直接改变状态。无需创建任何其他东西,以后可能会以错误的方式使用。直接用动作就行了

var store = new Vuex({
  state: {
    something: ''
  },
  actions: {
    async updateSomethingAsynchronnousWay ({state}, payload) {
      var response = await axios.get(payload.src)
      state.something = response.data.anyKey
    }
  }
})

new Vue({
  store
  el: '#app',
  created () {
    this.$store.dispatch({
      type: 'updateSomethingAsynchronnousWay,
      src: 'https//your.rest.api/something'
    })
  }
})