我试图在vuex商店的一个部分创建一个对象,然后将id传递给另一个对象,我不知道如何正确地做到这一点,因为突变不能返回任何返回的东西(在这种情况下,id)。
两个商店对象如下所示:
// store/report.js
const state = {
name: 'Untitled Report',
subReportIds: []
};
// store/subReport.js
const state = { ... }
我希望此操作创建空白报告,然后空白子报告,然后将子报告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)
}
};
我如何实现上述目标?
答案 0 :(得分:9)
对我来说,最好的方法就是派遣行动而不是提交突变。如果你看一下Vuex源代码中的方法,commit
只执行(所以是一个空格),dispatch
返回你从动作返回的值(这是一个函数)
对于我的行为,我总是返回一个承诺,以便我可以像上面提到的那样组成它们。这是一个例子。
fetchSomething ({ commit }) {
return mockApiGetIds()
.then(response => {
commit({
type: SOME_MUTATION,
ids: response
});
return response;
});
},
答案 1 :(得分:4)
免责声明:我不知道这是否真的是个好主意,但至少,它似乎行得通,对我来说,这比必须使用动作和承诺或生成ID更漂亮。在行动中...
随着您的突变,您可以传递参数。要从突变中返回一个值(如新创建的id),我将其写入该参数中的占位符:
someMutation(state, arg){
//...
arg.out = {
status : "succeed"
}
}
//...
this.$store.commit('someMutation', arg);
if(arg.out !== "succeed") console.log("ERROR");
答案 2 :(得分:1)
通过从突变中恢复来使它正常工作真是太好了...
请支持对问题进行跟踪: https://github.com/vuejs/vuex/issues/1437
将来可能会有这样的事情:
let myReturn = this.$store.commit('ADD_THING",{"name":"new_thing"});
// 'ADD_THING' adds a thing to an numerically indexed object and then returns the number.
console.log(myReturn); // {"id":42,"datestamp":1541145883085}