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

How to access the getter from another vuex module?

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

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

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

我需要访问另一个名为 filters 的 vuex 模块,我试过这个:

rootState.filters.activeFilters

其中 activeFilters 是我的 getter 但这不起作用。使用 rootState.filters.getters.activeFilters 也不起作用。

不得不仔细阅读文档,但我找到了它:

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

(Ctrl+F 在该页面搜索 RootGetters)

我的代码变成:

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

请注意,所有 rootGetter 都是全局的,您不再像 rootState 那样使用它,在 rootState 中您会在状态前加上模块名称。

您只需像这样从另一个模块调用 getter:

rootGetters.activeFilters

希望这对将来 运行 也参与其中的人有所帮助。

如果您想从模块访问 global/namespaced 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的访问方式,也包括actionmutations的用法,供参考。

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

如果您有嵌套(和命名空间)模块,您可以执行以下操作来访问嵌套在另一个模块(例如 Vue.js 中)的模块的 getter:

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