在 vuex getter 中,我知道可以从另一个 vuex 模块访问状态,如下所示:
pages: (state, getters, rootState) => {
console.log(rootState);
}
我如何从另一个 vuex 模块而不是状态访问 getter?
我有另一个需要访问的称为过滤器的 vuex 模块,我试过这个:
rootState.filters.activeFilters
activeFilters
是我的吸气剂,但这不起作用。使用 rootState.filters.getters.activeFilters
也不起作用。
不得不挖掘文档,但我找到了它:
https://vuex.vuejs.org/en/api.html
(Ctrl+F 在该页面上搜索 RootGetters)
我的代码变成:
pages: (state, getters, rootState, rootGetters) => {}
请注意,所有 rootGetter 都是全局的,您不再像 rootState 那样使用它,您可以在状态前加上模块名称。
您只需从另一个模块调用 getter,如下所示:
rootGetters.activeFilters
希望这将帮助将来遇到此问题的人。
如果您想从模块访问全局/命名空间 getter
,您可以这样做,
getters: {
// `getters` is localized to this module's getters
// you can use rootGetters via 4th argument of getters
someGetter (state, getters, rootState, rootGetters) {
rootGetters.someOtherGetter //'someOtherGetter' global getter
rootGetters['bar/someOtherGetter'] //'bar/someOtherGetter' namespaced getter
},
...
},
这里是访问actions
的方法,还包括action
和mutations
的用法供参考。
actions: {
// dispatch and commit are also localized for this module
// they will accept `root` option for the root dispatch/commit
someAction ({ dispatch, commit, getters, rootGetters }) {
rootGetters.someGetter //'someGetter' global getter
rootGetters['bar/someGetter'] //'bar/someGetter' namespaced getter
dispatch('someOtherAction') //'someOtherAction' local action
dispatch('someOtherAction', null, { root: true }) //'someOtherAction' namespaced action
commit('someMutation') //'someMutation' local mutation
commit('someMutation', null, { root: true }) //'someMutation' namespaced mutation
},
...
}
}
如果您有嵌套(和命名空间)模块,您可以执行以下操作来访问嵌套在另一个模块中的模块的 getter(例如在 Vue.js 中):
this.$store.getters['outerModuleName/innerModuleName/nameOfTheGetter']
rootGetters['moduleName/getterName']
。rootGetters['module/getterName']
getter 以返回一个函数,如链接示例中所示。完成后,您就可以通过rootGetters['module/getterName'](myArg)
将参数传递给返回的函数。