我无法使用Vuex在Vue中使用mapState获取数据

时间:2019-02-20 16:32:24

标签: vue.js vuex

我对mapState有点困惑...只需检查一下

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'
    }
...

我假设...mapState(['user'])返回user () { return this.$store.state.user}而没有data对象 就像LinusBorg在此线程https://forum.vuejs.org/t/dont-understand-how-to-use-mapstate-from-the-docs/14454/9

中解释的那样

您可以在此处查看完整的代码-> https://codesandbox.io/s/n5z02km81l

2 个答案:

答案 0 :(得分:1)

由于您的商店分为模块,因此您需要使用对象语法和mapState来访问子模块的状态:

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

https://codesandbox.io/s/nn0zo023mm

或者您可以将data存储区命名为命名空间,即,将namespaced: true,添加到data.js模块中,然后使用:

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

https://codesandbox.io/s/olp064qm55

答案 1 :(得分:0)

它不起作用,因为userdata的属性

您需要在商店中创建吸气剂,并在组件中创建mapGetters

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


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

组件

import { mapGetters } from 'vuex'

export default {

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