从另一个动作中调用一个动作
Call an action from within another action
我的操作设置如下:
get1: ({commit}) => {
//things
this.get2(); //this is my question!
},
get2: ({commit}) => {
//things
},
我希望能够从另一个动作中调用一个动作,因此在本例中我希望能够从 get1()
中调用 get2()
。这可能吗?如果可以,我该怎么做?
您可以访问第一个参数中传递的对象中的 dispatch
方法:
get1: ({ commit, dispatch }) => {
dispatch('get2');
},
这在 documentation 中有介绍。
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');
}
}
对于确实需要 payload
的操作
actions: {
BEFORE: async (context, payload) => {
},
AFTER: async (context, payload) => {
var payload = {}//prepare payload
await context.dispatch('BEFORE', payload);
}
}
我们也可以在调度时传递参数。
dispatch('fetchContacts', user.uid);
您可以通过第一个参数(上下文)访问调度方法:
export const actions = {
get({ commit, dispatch }) {
dispatch('action2')
}
}
但是,如果您使用命名空间,则需要指定一个选项:
export const actions = {
get({ commit, dispatch }) {
dispatch('action2', {}, { root: true })
}
}
我的操作设置如下:
get1: ({commit}) => {
//things
this.get2(); //this is my question!
},
get2: ({commit}) => {
//things
},
我希望能够从另一个动作中调用一个动作,因此在本例中我希望能够从 get1()
中调用 get2()
。这可能吗?如果可以,我该怎么做?
您可以访问第一个参数中传递的对象中的 dispatch
方法:
get1: ({ commit, dispatch }) => {
dispatch('get2');
},
这在 documentation 中有介绍。
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');
}
}
对于确实需要 payload
的操作actions: {
BEFORE: async (context, payload) => {
},
AFTER: async (context, payload) => {
var payload = {}//prepare payload
await context.dispatch('BEFORE', payload);
}
}
我们也可以在调度时传递参数。
dispatch('fetchContacts', user.uid);
您可以通过第一个参数(上下文)访问调度方法:
export const actions = {
get({ commit, dispatch }) {
dispatch('action2')
}
}
但是,如果您使用命名空间,则需要指定一个选项:
export const actions = {
get({ commit, dispatch }) {
dispatch('action2', {}, { root: true })
}
}