从vuex突变返回值?(新创建的对象的ID)

vue.js Vue.js

GO西门

2020-03-16

我正在尝试在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)
    }
};

我该如何实现以上目标?

第1815篇《从vuex突变返回值?(新创建的对象的ID)》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
L猴子 2020.03.16

因此,对我而言最好的方法是调度操作而不是执行突变。如果您查看Vuex源代码中的方法,则commit仅执行(因此是一个void)并dispatch返回您从操作返回的值(这是一个函数)

对于我的行为,我始终会兑现承诺,以便像您在上面提到的那样撰写它们。这是一个例子。

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

      return response;
    });
  },

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android