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

新手上路,请多包涵

在 vuex getter 中,我知道可以从另一个 vuex 模块访问状态,如下所示:

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

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

我有另一个需要访问的称为 过滤器 的 vuex 模块,我试过这个:

 rootState.filters.activeFilters

activeFilters 是我的吸气剂,但这不起作用。使用 rootState.filters.getters.activeFilters 也不起作用。

原文由 Stephan-v 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 844
2 个回答

不得不挖掘文档,但我找到了它:

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

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

我的代码变成:

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

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

您只需从另一个模块调用 getter,如下所示:

 rootGetters.activeFilters

希望这将帮助将来遇到此问题的人。

原文由 Stephan-v 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果你想从模块访问全局/命名空间 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
      },
      ...
    }
  }

原文由 Kiran Maniya 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题