问题描述
是否可以在命名空间模块之间分派动作?
Is it possible to dispatch an action between namespaced modules?
例如我有 vuex 模块游戏板"和通知".每个都是命名空间的.我想从游戏板向通知模块发送一个动作.
E.g. I have vuex modules "gameboard" and "notification". Each are namespaced. I would like to dispatch an action from the gameboard to the notification module.
我想我可以在调度操作名称中使用模块名称,如下所示:
I thought I could use the module name in the dispatch action name like this:
// store/modules/gameboard.js
const actions = {
myaction ({dispatch}) {
...
dispatch('notification/triggerSelfDismissingNotifcation', {...})
}
}
// store/modules/notification.js
const actions = {
triggerSelfDismissingNotification (context, payload) {
...
}
}
但是当我尝试这样做时,我得到了一些错误,让我觉得 vuex 试图在我的游戏板模块中分派一个动作:
But when I try to do this I get errors that make me thing vuex is trying to dispatch an action within my gameboard module:
[vuex] 未知本地动作类型:notification/triggerSelfDismissingNotification,全局类型:gameboard/notification/triggerSelfDismissingNotification
有没有办法从 vuex 模块调度到模块,或者我需要在根 vuex 实例中创建某种桥接吗?
Is there a way of dispatching from vuex module to module or do I need to create some kind of a bridge in the root vuex instance?
推荐答案
你只需要指定你是从根上下文调度:
You just need to specify that you're dispatching from the root context:
// from the gameboard.js vuex module
dispatch('notification/triggerSelfDismissingNotifcation', {...}, {root:true})
现在当分派到达根时,它将拥有到通知模块的正确命名空间路径(相对于根实例).
Now when the dispatch reaches the root it will have the correct namespace path to the notifications module (relative to the root instance).
这是假设您在 vuex 商店模块上设置 namespaced: true
.
This is assuming you're setting namespaced: true
on your vuex store module.
这篇关于有没有办法在两个命名空间的 vuex 模块之间分派动作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!