将参数传递给 mapGetters

Pass params to mapGetters

我在我的组件中使用 vuexmapGetters 助手。我得到了这个功能:

getProductGroup(productIndex) {
  return this.$store.getters['products/findProductGroup'](productIndex)
}

是否可以通过某种方式将其移动到 mapGetters?问题是我还向函数传递了一个参数,所以我找不到将其放入 mapGetters

的方法

如果您的 getter 接受这样的参数:

getters: {
  foo(state) {
    return (bar) => {
      return bar;
    }
  }
}

然后可以直接映射getter:

computed: {
  ...mapGetters(['foo'])
}

然后传入参数给this.foo:

mounted() {
  console.log(this.foo('hello')); // logs "hello"
}

抱歉,我和@Golinmarq 一起解决这个问题。

对于任何正在寻找不需要在模板中执行计算属性的解决方案的人来说,您不会开箱即用。

https://github.com/vuejs/vuex/blob/dev/src/helpers.js#L64

这里有一个小片段,我用附加参数来 curry mappedGetters。这假定您的 getter returns 是一个接受您的附加参数的函数,但您可以很容易地对其进行改造,以便 getter 同时接受状态和附加参数。

    import Vue from "vue";
    import Vuex, { mapGetters } from "vuex";

    Vue.use(Vuex);

    const store = new Vuex.Store({
        modules: {
            myModule: {
                state: {
                    items: [],
                },
                actions: {
                    getItem: state => index => state.items[index]
                }
            },
        }
    });


    const curryMapGetters = args => (namespace, getters) =>
        Object.entries(mapGetters(namespace, getters)).reduce(
            (acc, [getter, fn]) => ({
            ...acc,
            [getter]: state =>
                fn.call(state)(...(Array.isArray(args) ? args : [args]))
            }),
            {}
        );

    export default {
        store,
        name: 'example',
        computed: {
            ...curryMapGetters(0)('myModule', ["getItem"])
        }
    };

要点在这里https://gist.github.com/stwilz/8bcba580cc5b927d7993cddb5dfb4cb1