【问题标题】:Pass params to mapGetters将参数传递给 mapGetters
【发布时间】:2017-10-04 01:32:15
【问题描述】:

我在组件中使用 vuexmapGetters 助手。我得到了这个功能:

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

是否可以以某种方式将其移至mapGetters?问题是我还向函数传递了一个参数,所以我找不到将其放入 mapGetters

的方法

【问题讨论】:

    标签: vuejs2 vuex


    【解决方案1】:

    抱歉,我和@Golinmarq 一起讨论这个问题。

    对于任何寻求解决方案的人,如果您不需要在模板中执行计算的属性,您将无法立即使用它。

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

    这里有一个小sn-p,我用其他参数来咖喱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

    【讨论】:

      【解决方案2】:

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

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

      那么就可以直接映射getter了:

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

      只需将参数传递给this.foo

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

      【讨论】:

      • 我认为他指的是计算属性
      • @Golinmarq,我认为他没有这样做,因为他询问了mapGetters,然后接受了我的回答。如果您有类似的与计算属性相关的问题尚未在网站上得到解答,您可以单独发帖。
      猜你喜欢
      • 1970-01-01
      • 2018-01-08
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 2013-11-19
      • 2011-01-06
      相关资源
      最近更新 更多