Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass params to mapGetters

Tags:

vuejs2

vuex

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

like image 297
Victor Avatar asked May 05 '17 14:05

Victor


2 Answers

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"
}
like image 117
thanksd Avatar answered Oct 21 '22 05:10

thanksd


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

like image 5
stwilz Avatar answered Oct 21 '22 06:10

stwilz