Pass params to mapGetters

烈酒焚心 提交于 2020-06-24 07:14:19

问题


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


回答1:


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"
}



回答2:


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



来源:https://stackoverflow.com/questions/43807123/pass-params-to-mapgetters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!