如何从另一个 uex 模块访问 getter?

在 vuex getter 中,我知道可以像下面这样从另一个 vuex 模块访问状态:

pages: (state, getters, rootState) => {
console.log(rootState);
}

但是,如何从另一个 vuex 模块而不是状态访问 getter?

我还需要访问另一个名为 过滤器的 vuex 模块,我试过这样做:

rootState.filters.activeFilters

其中 activeFilters是我的读取器,但这不工作。使用 rootState.filters.getters.activeFilters也不工作。

66548 次浏览

Had to dig through the documentation but I found it:

https://vuex.vuejs.org/en/api.html

(Ctrl+F search for RootGetters on that page)

My code becomes:

pages: (state, getters, rootState, rootGetters) => {}

Beware that all rootGetters are global and you no longer use it like rootState where you would prefix the state by the module name.

You simply call a getter from another module like so:

rootGetters.activeFilters

Hopefully this will help someone out in the future who is running into this as well.

If you want to access global/namespaced getter from the module, Here is how you can it,

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
},
...
},

Here is the way to access actions, Also includes usage of action and mutations for the reference.

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
},
...
}
}

If you have nested (and namespaced) modules, you can do the following to access the getters of a module that is nested inside another module (e.g. in Vue.js):

this.$store.getters['outerModuleName/innerModuleName/nameOfTheGetter']