我对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
答案 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
})
答案 1 :(得分:0)
它不起作用,因为user
是data
的属性
您需要在商店中创建吸气剂,并在组件中创建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'])
}
}