【问题标题】:How to access the getter from another vuex module?如何从另一个 vuex 模块访问 getter?
【发布时间】:2018-02-10 11:34:45
【问题描述】:

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

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

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

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

rootState.filters.activeFilters

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

【问题讨论】:

    标签: javascript vue.js vuejs2 vuex


    【解决方案1】:

    不得不翻阅文档,但我找到了:

    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) 将参数传递给返回的函数。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-12
      • 2021-09-15
      • 2019-11-17
      • 2018-02-22
      • 2017-10-01
      • 2019-04-11
      • 1970-01-01
      相关资源
      最近更新 更多