微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vue.js – Vuex mapstate对象未定义和“[vuex]未知突变类型:”

我是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");

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐