Vuejs2 Vuex变异返回上次插入

Vuejs2 Vuex变异返回上次插入,vuejs2,vuex,Vuejs2,Vuex,我想返回一个从突变到动作的值。 在这种情况下,我需要最后插入的对象: 在我看来,工作很好: mutations: { insert(state, item) { const guid = Math.floor(Math.random() * 6) + 1; // any sense, just example item.guid = guid; state.data.push(item); return guid; }, }, 在我的行动中,为召唤而不是

我想返回一个从突变到动作的值。 在这种情况下,我需要最后插入的对象:

在我看来,工作很好:

mutations: {
  insert(state, item) {
    const guid = Math.floor(Math.random() * 6) + 1; // any sense, just example
    item.guid = guid;
    state.data.push(item);
    return guid;
  },
},
在我的行动中,为召唤而不是回报而努力:

actions: {
  insert ({ commit }, data) {
    return new Promise((resolve) => {
      const guid = commit('insert', event);
      resolve(guid); // resolve undefined
    });
  },
},
有没有办法返回guid? 我需要它发射后与我的组件


谢谢

您可以通过将状态数据传递到操作insert{commit,state},data{

例如:

actions: {
  insert ({ commit, state }, data) {
    return new Promise((resolve) => {
      commit('insert', event);
      const guid = state.data[state.data.length].guid
      resolve(guid); // resolve undefined
    });
  },
},

而且,正如在评论中提到的,最佳实践是将GUID生成计算留给一个操作,而只是真正地提交变异中的状态

也就是说,你可以发送一个回调给变异并调用它。只要确保回调代码是简单和同步的,如果不是,请参阅下面

const store=新的Vuex.store{ 严格:是的, 声明:{ 数据:[] }, 突变:{ insertstate,{item,callback}{ const guid=Math.floorMath.random*600+1;//任何意义,仅举个例子 item.guid=guid; state.data.pushitem; callbackguid; }, }, 行动:{ 插入{commit},数据{ 返回新PromiseSolve=>{ 提交'insert',{item:data,callback:resolve}; }; }, }, }; 新Vue{ 百货商店 el:“应用程序”, 数据:{insertedGuid:'单击下面的按钮'}, 方法:{ go:异步函数{ const guid=wait this.$store.dispatch'insert',{name:Alice}; this.insertedGuid=guid; } }, 计算:{ 数据:函数{ 返回此。$store.state.data } }, } 存储区的数据:{{datadata}}

insertedGuid:{{insertedGuid}}

单击以插入
虽然这并不能完全回答您的问题,但我认为通常的做法是避免在变异中生成数据。然后,您的操作将具有GUID并将其传递给变异。绝对是这样!谢谢。