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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45999623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:17:28  来源:igfitidea点击:

How to access the getter from another vuex module?

javascriptvue.jsvuejs2vuex

提问by Stephan-v

Within a vuex getter I know it is possible to access the state from another vuex module like so:

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

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

How can I access a getter from another vuex module instead of the state though?

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

I have another vuex module called filtersthat I need to access, I have tried this:

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

rootState.filters.activeFilters

Where activeFiltersis my getter but this does not work. using rootState.filters.getters.activeFiltersalso does not work.

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

回答by Stephan-v

Had to dig through the documentation but I found it:

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

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

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

(Ctrl+F search for RootGetters on that page)

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

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.

请注意,所有 rootGetter 都是全局的,您不再像 rootState 那样使用它,在这种情况下,您将使用模块名称作为状态前缀。

You simply call a getter from another module like so:

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

rootGetters.activeFilters

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

希望这将有助于将来也遇到此问题的人。

回答by Meena Chaudhary

This example is for accessing getter from one module into another module's action.

此示例用于从一个模块访问 getter 到另一个模块的操作。

Below is user.jsmodule with getter

下面是user.js带有吸气剂的模块

isUserAuthenticated: state => {
  return !(state.token == null);
}

To access this in post.jsmodule action

post.js模块操作中访问它

validateAction(vuexContext, actionDetails) {
  return new Promise((resolve, reject) => {

    if (vuexContext.rootGetters["user/isUserAuthenticated"]) {
        console.log("User is authenticated");
    } else {
        console.log("User is not authenticated");
    }
  });
...
}

Hope this is helpful.

希望这是有帮助的。