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

Ste*_*n-v 40 javascript vue.js vuex vuejs2

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

pages: (state, getters, rootState) => {
    console.log(rootState);
}
Run Code Online (Sandbox Code Playgroud)

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

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

rootState.filters.activeFilters
Run Code Online (Sandbox Code Playgroud)

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

Ste*_*n-v 83

不得不仔细阅读文档,但我发现它:

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

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

我的代码变成:

pages: (state, getters, rootState, rootGetters) => {}
Run Code Online (Sandbox Code Playgroud)

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

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

rootGetters.activeFilters
Run Code Online (Sandbox Code Playgroud)

希望这将有助于将来遇到这种情况的人.

  • 如果要访问的getter模块是命名空间,则需要使用`rootGetters ['moduleName/getterName']`. (71认同)
  • @JohnOveriron您链接到的示例是一个吸气剂,该吸气剂返回一个函数,该函数本身接受一个参数(有细微的区别)。但这并非开箱即用。您需要专门实现您的rootGetters ['module / getterName'] getter来返回函数,如链接示例中所示。完成后,您将可以通过rootGetters ['module / getterName'](myArg)将参数传递给返回的函数。 (2认同)

Kir*_*iya 24

如果你想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
    },
    ...
},
Run Code Online (Sandbox Code Playgroud)

这里是访问方式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
      },
      ...
    }
  }
Run Code Online (Sandbox Code Playgroud)