ChatGPT解决这个技术问题 Extra ChatGPT

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

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

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

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

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

rootState.filters.activeFilters

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


S
Stephan-v

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

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

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

我的代码变成:

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

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

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

rootGetters.activeFilters

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


如果您访问的 getter 模块是命名空间的,则需要使用 rootGetters['moduleName/getterName']
@thanksd,如果我们想将参数传递给“moduleName/getterName”,那么语法是什么?
@JohnOveriron 吸气剂不接受争论,所以我不确定你指的是什么。您的 getter 可以返回一个接受参数的函数,您可以这样做:stackoverflow.com/questions/41503527/…
他们是这样。即使在您指出的讨论中,也有带有参数的 getter 示例。在官方文档中:vuex.vuejs.org/guide/getters.html#method-style-access 我只是很难使用 rootGetters['module/getterName'] 表示法用参数调用它们
@JohnOveriron您链接到的示例是一个getter,它返回一个本身接受参数的函数(这是一个微妙的区别)。但这并不是开箱即用的。您需要专门实现您的 rootGetters['module/getterName'] getter 以返回一个函数,如链接示例中所示。完成后,您就可以通过 rootGetters['module/getterName'](myArg) 将参数传递给返回的函数。
K
Kiran Maniya

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

T
Timm

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

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