我是vue.js和vuex的新手,我对mapstate对象有一个问题,首先我在我的商店中只有一个模块:
-Store
-index.js
-mutations.js
-actions.js
-state.jsstate.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文件中,现在当我尝试获取对象时,我总是得到undefined
commons.js
// state
const state = {
userInfo: {
messages: [{ 1: 'test', 2: 'test' }],
notifications: [],
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对象吗?
谢谢。
发布于 2018-03-09 12:31:28
考虑到:
vuex未知突变类型:
由于您现在是命名空间您的commons模块,所以模块的突变现在必须是前缀。
所以,假设你有变异,就像:
const mutations = {
changeName(state, data) {
state.name = data;
}
}
export default {
namespaced: true,
actions,
mutations,
state
}你用它就像:
this.$store.commit('changeName', "New Name");现在就像这样使用它:
this.$store.commit('commons/changeName', "New Name");发布于 2018-03-09 12:00:09
您必须将每个模块定义为一个单独的存储区,下面是一些伪示例。
// authStore.js
import mutations from './authMutations'
import actions from './authActions'
import getters from './authGetters'
const initialState = {
...
}
export default {
state: initialState,
mutations,
actions,
getters
}然后,注册模块。
import authStore from './authStore'
const store = new Vuex.Store({
modules: {
{...authStore, namespaced: true},
{...postStore, namespaced: true} // some other module defined like auth
}
})
new Vue({
....
store: store
})然后,在组件上使用它:
import { createNamespacedHelpers } from 'vuex'
// map state and actions of the module
const { mapState, mapActions } = createNamespacedHelpers('auth')
export default {
computed: {
...mapState({
prop1: 'prop1'
})
}
}发布于 2018-03-09 12:07:51
我想您已经通过在模块中添加namespaced: true来命名模块。
因此,您应该将模块名作为第一个参数传递给mapState帮助程序,以便使用该模块作为上下文完成所有绑定。请参阅用名称空间绑定帮助程序
computed: {
...mapState('commons' , ["userInfo"])
}https://stackoverflow.com/questions/49192961
复制相似问题