[英]Vuex: Store module cyclic dependency
I have the following situation: 我有以下情况:
store/index.js 商店/index.js
import moduleA from '@/store/module-a';
import moduleB from '@/store/module-b';
export default new Vuex.Store({
modules: {
A: moduleA,
B: moduleB
}
});
store/module-a.js store / module-a.js
export default {
namespaced: true,
state: {
val: // constructed using localStorage
}
};
store/module-b.js 商店/模块-b.js
export default {
namespaced: true,
state: {
val: // requires store/module-a.js state.val to construct
},
mutations: {
add: function () {
// requires store/module-a.js state.val
}
}
};
If I try to import store from '@/store
inside of module B, and then access store.state.A.val
, I'd get a cyclic dependency, where store --> moduleB --> store
. 如果我尝试import store from '@/store
模块B内的import store from '@/store
,然后访问store.state.A.val
, store.state.A.val
得到一个循环依赖关系,其中store --> moduleB --> store
。
I can construct the store.state.A.val
inside of module B, but that would be duplicating logic, and since module A is being loaded first, it would be nice if I could just access it from module A. Is that possible? 我可以在模块B内构造store.state.A.val
,但这将是重复的逻辑,并且由于首先加载了模块A,所以如果我只能从模块A进行访问,那就太好了。这可能吗?
I'd construct your b store's val as a default, not including any info from settings. 我会将b商店的val构造为默认值,不包括设置中的任何信息。 Then have a mutation or action that sets it up properly from settings (a). 然后进行突变或从设置(a)中正确设置它的操作。 Probably should be an Action, since Mutations only get the local state, whereas Actions get a context that includes the rootState
from which you can access the other modules. 可能应该是一个Action,因为Mutations仅获得本地状态,而Actions获得一个包含rootState
的上下文,您可以从该上下文访问其他模块。 Alternatively you can just use a getter for b.val
; 或者,您可以只将getter用于b.val
; getters have access to rootState
(and rootGetters
) as well. 获取器也可以访问rootState
(和rootGetters
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.