将params传递给mapGetters

时间:2017-05-05 14:08:35

标签: vuejs2 vuex

我在我的组件中使用vuexmapGetters帮助器。我有这个功能:

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

是否有可能以某种方式将其移至mapGetters?问题是我也将一个参数传递给函数,所以我找不到一种方法将它放在mapGetters

2 个答案:

答案 0 :(得分:23)

如果你的getter接受了这样的参数:

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

然后你可以直接映射吸气剂:

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

然后将参数传递给this.foo

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

答案 1 :(得分:0)

对不起,我和@Golinmarq在一起。

对于那些寻求解决方案而无需在模板中执行计算出的属性的人来说,您将无法立即使用它。

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

这是我用来带附加参数的mappedGetters的一些摘要。假定您的getter返回了一个带有附加参数的函数,但是您可以很容易地对其进行改进,以便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

相关问题