我是vue.js和vuex的新手,我遇到了mapstate对象的问题,首先我店里只有一个模块:
-Store -index.js -mutations.js -actions.js -state.js
state.js:
export default { userInfo: { messages: [{ 1: 'test',2: 'test' }],notifications: [],tasks: [] } }
因此,当我尝试访问userInfo对象时,一切正常:
computed: { ...mapState(["userInfo"]),}
然后我决定创建模块:
-Store -modules -ldap.js -commons.js -index.js
所以userInfo在commons.js文件中,现在当我尝试获取对象时,我总是得到未定义:
commons.js
// state const state = { userInfo: { messages: [{ 1: 'test',tasks: [] } } export default { actions,mutations,state }
Component.vue
computed: { ...mapState(["userInfo"]),// <---- undefined }
main.js:
import Vue from 'vue' import Vuex from 'vuex' import commons from './commons' import ldap from './modules/ldap' Vue.use(Vuex) export default new Vuex.Store({ modules : { commons,ldap } })
你能告诉我如何访问userInfo对象吗?
谢谢.
解决方法
考虑到:
>您的commons.js如下:
// state const state = { userInfo: { messages: [{ 1: 'test',tasks: [] } } export default { namespaced: true,// <== make sure this is defined actions,state }
>并且main.js导入它像:
import commons from './commons' // .. export default new Vuex.Store({ modules : { commons,ldap } })
>然后在Component.vue上更新:
import { mapState } from 'vuex' // ... computed: { ...mapState('commons',["userInfo"]),// <== add module name here }
要么
import { createNamespacedHelpers } from 'vuex' const { mapState,mapActions } = createNamespacedHelpers('commons') // ... notice module name above ^^^^^^^^^ computed: { ...mapState(["userInfo"]),}
“[vuex] unkNown mutation type: “
由于您现在是命名空间的公共模块,因此现在必须为模块的突变添加前缀.
所以,假设你有一个突变:
const mutations = { changeName(state,data) { state.name = data; } } export default { namespaced: true,actions,state }
你使用它像:
this.$store.commit('changeName',"New Name");
现在使用它像:
this.$store.commit('commons/changeName',"New Name");