16

I know how to use mapGetters in a single situation, but not both.

Example, I have firstRootGetter inside store/index.js, so I will call ...mapGetters(['firstRootGetter']) in vue component.

If I have firstModuleGetter and secondModuleGetterinside store/modules/post.js, I will call ...mapGetters('post', ['firstModuleGetter', 'secondModuleGetter'])

My question is, how do I call them in single ...mapGetters. Is it possible?

Right now I have to write 2 lines to call them separately.

Sang Dang
  • 501
  • 1
  • 11
  • 26

2 Answers2

44

Yes it is possible, you must supply the namespace to the mapGetters helper in each line, though:

...mapGetters({
  exampleGetter: 'myModule1/exampleGetter',
  anotherGetter: 'myModule2/anotherGetter',
})

If you're trying to combine them into a single getter, use a root action that reads both module stores and returns a combined object. Then mapActions like you would mapGetters.

  • Thank you but I don't ask for combining them into a single getter. I'm asking about how to use the `mapGetters`. In your answer, when I try to do: `...mapGetters([ 'firstRootGetter', 'myModule1/exampleGetter', 'myModule2/anotherGetter', ])` it does not work. – Sang Dang Jan 22 '18 at 07:55
  • 3
    See my answer again, I've edited how the getters are passed in. Use an object `{}` instead of an array `[]` and provide aliases for the getters. Doing this you can use `this.exampleGetter` and `this.anotherGetter`. –  Jan 22 '18 at 07:58
  • Glad it helped. Ta. –  Jan 22 '18 at 08:04
  • Oh are you real Linus Borg??? You are my idol! Back to the question, yes, of course, it worked in 2 getters, just wondering if I could make it in one place. Don't know why I like to call it at once. Again I'm really glad that you answer my question. – Sang Dang Jan 22 '18 at 10:26
12
computed: {
        ...mapGetters('module1', ['getQuestions', 'getAnswers']),
        ...mapGetters('module2', ['getGrades'])
    },

This is the syntax used:

 ...mapGetters('some/nested/module', [
    'someGetter', // -> this.someGetter
    'someOtherGetter', // -> this.someOtherGetter
  ])
James Ikubi
  • 2,552
  • 25
  • 18