33

I use vuex and mapGetters helper in my component. I got this function:

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

Is it possible to move this somehow to mapGetters? The problem is that I also pass an argument to the function, so I couldn't find a way to put this in mapGetters

Victor
  • 5,073
  • 15
  • 68
  • 120

2 Answers2

45

If your getter takes in a parameter like this:

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

Then you can map the getter directly:

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

And just pass in the parameter to this.foo:

mounted() {
  console.log(this.foo('hello')); // logs "hello"
}
thanksd
  • 54,176
  • 22
  • 157
  • 150
  • 6
    I think he refers to in a computed property – Golinmarq Mar 21 '19 at 16:35
  • 1
    @Golinmarq, I don't think he does since he asked about `mapGetters` and then accepted my answer. If you have a similar question related to computed properties which hasn't already been answered on the site, you could make a separate post for it. – thanksd Mar 21 '19 at 16:39
5

Sorry, I'm with @Golinmarq on this one.

For anyone looking for a solution to this where you don't need to execute your computed properties in your template you wont get it out of the box.

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

Here's a little snippet I've used to curry the mappedGetters with additional arguments. This presumes your getter returns a function that takes your additional arguments but you could quite easily retrofit it so the getter takes both the state and the additional arguments.

    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"])
        }
    };

Gist is here https://gist.github.com/stwilz/8bcba580cc5b927d7993cddb5dfb4cb1

stwilz
  • 2,226
  • 2
  • 21
  • 24