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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...