我有以下设置为我的行动:

get1: ({commit}) => {
  //things
  this.get2(); //this is my question!
},
get2: ({commit}) => {
  //things
},

我希望能够从一个动作中调用另一个动作,因此在本例中,我希望能够从get1()中调用get2()。这可能吗?如果可能,我该怎么做?


当前回答

export actions = {
  GET_DATA (context) {
     // do stuff
     context.dispatch('GET_MORE_DATA');
  },

  GET_MORE_DATA (context) {
    // do more stuff
  }
}

其他回答

你可以访问第一个参数传递的对象中的dispatch方法:

get1: ({ commit, dispatch }) => {
  dispatch('get2');
},

这在文档中有介绍。

export actions = {
  GET_DATA (context) {
     // do stuff
     context.dispatch('GET_MORE_DATA');
  },

  GET_MORE_DATA (context) {
    // do more stuff
  }
}

对于不需要有效载荷的操作

actions: {
    BEFORE: async (context, payload) => {
    },
    AFTER: async (context, payload) => {
        await context.dispatch('BEFORE');
    }
}

对于需要有效载荷的操作

actions: {
    BEFORE: async (context, payload) => {
    },
    AFTER: async (context, payload) => {
        var payload = {}//prepare payload
        await context.dispatch('BEFORE', payload);
    }
}

我们也可以在调度时传递参数。

dispatch('fetchContacts', user.uid);

你可以通过第一个参数(context)来访问分派方法:

导出const动作= { Get({提交,分派}){ 调度(“action2”) } }

然而,如果你使用命名空间,你需要指定一个选项:

导出const动作= { Get({提交,分派}){ Dispatch ('action2', {}, {root: true}) } }