将params传递给mapGetters

Vic*_*tor 15 vuex vuejs2

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

getProductGroup(productIndex) {
  return this.$store.getters['products/findProductGroup'](productIndex)
}
Run Code Online (Sandbox Code Playgroud)

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

tha*_*ksd 27

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

getters: {
  foo(state) {
    return (bar) => {
      return bar;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以直接映射getter:

computed: {
  ...mapGetters(['foo'])
}
Run Code Online (Sandbox Code Playgroud)

并将参数传递给this.foo:

mounted() {
  console.log(this.foo('hello')); // logs "hello"
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为他指的是计算属性 (2认同)

stw*_*ilz 5

抱歉,我和 @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"])
        }
    };
Run Code Online (Sandbox Code Playgroud)

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