从vuex变异返回值?(新创建的对象的id)

Rud*_*udi 15 vue.js vuex vuejs2

我试图在vuex商店的一个部分创建一个对象,然后将id传递给另一个对象,我不知道如何正确地做到这一点,因为突变不能返回任何返回(在这种情况下,id ).

两个商店对象看起来像这样:

// store/report.js
const state = {
    name: 'Untitled Report',
    subReportIds: []
};

// store/subReport.js
const state = { ... }
Run Code Online (Sandbox Code Playgroud)

我希望此操作创建空白报告,然后空白子报告,然后将子报告ID分配给新创建的报告.(子报告是独立的实体,可以由多个报告使用,因此存储中的区域不同)

const actions = {
    createNewReport({ state, commit }) {
        commit(mutationTypes.CREATE_NEW_REPORT)
        // below doesn't work - i can't get return from mutation
        let newSubreportId = commit(mutationTypes.ADD_NEW_SUBREPORT)
        // if this worked, i'd then do something like
        commit(mutationTypes.ADD_SUBREPORT_TO_REPORT, newSubreportId)
    }
};
Run Code Online (Sandbox Code Playgroud)

我怎样才能实现上述目标?

Aus*_*tio 12

因此,最好的方法是发送行动而不是提交突变.如果查看Vuex源代码中的方法,commit只执行(所以是void)并dispatch返回从action返回的值(这是一个函数)

对于我的行为,我总是返回一个承诺,以便我可以像上面提到的那样组成它们.这是一个例子.

fetchSomething ({ commit }) {
  return mockApiGetIds()
    .then(response => {
      commit({
        type: SOME_MUTATION,
        ids: response
      });

      return response;
    });
  },
Run Code Online (Sandbox Code Playgroud)

  • 最惯用的解决方案。 (2认同)

hl0*_*37_ 5

免责声明:我不知道这是否真的是一个好主意,但至少,它似乎行得通,对我来说,这比必须使用操作和承诺或在操作中生成ID更漂亮。

通过您的突变,您可以传递参数。要从变异中返回一个值(如新创建的id),我将其写入该参数中的占位符:

someMutation(state, arg){
   //...
   arg.out = {
      status : "succeed"
   }
}

//...

this.$store.commit('someMutation', arg);
if(arg.out !== "succeed") console.log("ERROR");
Run Code Online (Sandbox Code Playgroud)

  • 虽然这确实有效,但依靠改变参数来表示结果会增加复杂性,我认为这不会让其他用户感到惊讶。 (2认同)