gpt4 book ai didi

vue.js - Vuex mapstate 对象未定义和 "[vuex] unknown mutation type: "

转载 作者:搜寻专家 更新时间:2023-10-30 22:18:44 24 4
gpt4 key购买 nike

我是 vue.js 和 vuex 的新手,我对 mapstate 对象有疑问,首先我的商店中只有一个模块:

-Store
-index.js
-mutations.js
-actions.js
-state.js

状态.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
}

ma​​in.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', 2: 'test' }],
    notifications: [],
    tasks: []
    }
    }

    export default {
    namespaced: true, // <== make sure this is defined
    actions,
    mutations,
    state
    }
  • ma​​in.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: "

由于您现在正在命名您的 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");

关于vue.js - Vuex mapstate 对象未定义和 "[vuex] unknown mutation type: ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49192961/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com