vuex namespaced mapState with multiple modules

Viewed 31209

I must be missing something. How can I use vuex mapState with multiple modules?

As far as understand, besides passing an object as argument, namespaced mapState can take two arguments: namespace and an array of object names denoting the members of modules. Like this

// an imcomplete vue
export default {
   computed: mapState('user', ['addresses', 'creditCards']) 
};

But what if i'd like to add objects from a second namespace to computed? e.g. vendor like this:

mapState('vendor', ['products', 'ratings']) 

Currently I am merging both mapState like this:

let userMapState = mapState('user', ['addresses', 'creditCards']); 
let vendorMapState = mapState ('vendor', ['products', 'ratings']);
let mergedMapStates = Object.assign({}, userMapState, vendorMapState);

And then:

// an imcomplete vue
export default {
    computed: mergedMapStates
};

It works, but it's hardly the right way to do it. Or is it?

5 Answers

This is from the vuex docs, you can do it all within one ...mapState({}). Documentation

computed: {
  ...mapState({
    a: state => state.some.nested.module.a,
    b: state => state.some.nested.module.b
  })
},

Edit 2019

You can also pass a path to your nested module and make the module references cleaner (thanks @gijswijs)

computed: {
  ...mapState('some/nested/module', {
    a: state => state.a,
    b: state => state.b
  })
},

You can try this if you have no too many namespaces:

    ...mapState({
      userAddresses: 'user/addresses',
      userCreditCards: 'user/creditCards'

      vendorProducts: 'vendor/products',
      vendorRatings: 'vendor/ratings',          
    }) 

You couldĀ also use Object.assign like this. Similar to your current solution but a bit cleaner.

    computed: Object.assign(
        mapState('user', ['addresses', 'creditCards']),
        mapState('vendor', ['products', 'ratings']
    )

Make use of spread operator to access multiple module State values

 ...mapState('user', {
     isLoggedIn: ({ activeUser }) => !!activeUser?.id
  }),
   ...mapState('quizzes', ['getCategories'])
Related