Marcogomesr
Marcogomesr

Reputation: 2672

I can't any get data using mapState in Vue using Vuex

I'm bit confused with mapState...just check this out

index.vue ...

    computed: {

        //this doesn't work
        ...mapState(['user']), 

        // this works 
        user () { 
            return this.$store.state.data.user
        }
    }

modules/data.js

...

   const state = {
        msg: 'Tom'
    }
...

I assuming ...mapState(['user']) returns user () { return this.$store.state.user} without data object like LinusBorg explains in this thread https://forum.vuejs.org/t/dont-understand-how-to-use-mapstate-from-the-docs/14454/9

you can check the full code here --> https://codesandbox.io/s/n5z02km81l

Upvotes: 1

Views: 5042

Answers (2)

Miguel Coder
Miguel Coder

Reputation: 1954

It's not working because user is a property of data

You need to create getters in your store and us mapGetters in your component.

https://vuex.vuejs.org/guide/getters.html


export default store = new Vuex.Store({
  state: { ... }
  getters: {
    user => (state) => state.data.user
  }
}

Component

import { mapGetters } from 'vuex'

export default {

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

Upvotes: 0

akuiper
akuiper

Reputation: 214927

Since your store is divided into modules, you need to use object syntax with mapState to access state from a submodule:

...mapState({
  msg: state => state.data.msg
})

https://codesandbox.io/s/nn0zo023mm

Or you can make the data store namespaced, i.e. add namespaced: true, to data.js module, then access it with:

...mapState('data', {
  msg: state => state.msg
})

https://codesandbox.io/s/olp064qm55

Upvotes: 4

Related Questions