Vue.js Vuex mapState返回的对象不是数组?
我想使用v-for在对象数组上循环。但是,“我的状态”返回一个包含对象数组的对象:Vue.js Vuex mapState返回的对象不是数组?,vue.js,vuex,Vue.js,Vuex,我想使用v-for在对象数组上循环。但是,“我的状态”返回一个包含对象数组的对象: { "todos": [ { "id": "x", "description": "y" }, { "id": "a", "description": "b" } ] } 这导致v-for不起作用。如果改用getter,它会像预期的那样返回对象数组: [ { "id": "x", "description": "y" }, { "id": "a", "description": "b" } ] 这是正常的行为
{ "todos": [ { "id": "x", "description": "y" }, { "id": "a", "description": "b" } ] }
这导致v-for不起作用。如果改用getter,它会像预期的那样返回对象数组:
[ { "id": "x", "description": "y" }, { "id": "a", "description": "b" } ]
这是正常的行为吗
使用mapState:
<template>
<div class="content-center">
{{todos}}
</div>
</template>
....
import {mapActions, mapGetters, mapState} from 'vuex';
export default {
....
computed: mapState(['todos'])
}
将模块命名为命名空间解决了这个问题,尽管我不太清楚为什么 根据,默认情况下,
mapState
helper将返回一个对象
getter返回数组而不是对象的原因是getter必须始终是函数。在您的例子中,单行箭头函数state=>state.todos
访问对象,然后隐式返回对象内的状态
您可以打开字符串数组以执行其他操作(即访问对象),而不是像mapState(['todos'])
那样将字符串数组传递给帮助器,如下图所示:
请注意,您基本上是以与getter相同的方式访问状态。。。只有这一次,您才在computed
部分下的组件中执行此操作
注意:如果您有嵌套模块,您可能希望绑定名称空间,如中所示
此外,如果不需要使用多个存储状态属性或getter,则可以使用this.$store
快捷方式访问单个todos
属性:
computed: {
todos() {
return this.$store.state.{module_filename}.todos
}
}
希望有帮助
将模块命名为命名空间解决了这个问题,尽管我不太清楚为什么 只有操作、突变和getter在全局命名空间中注册,而不是在模块状态中注册。 因此名称空间解决了您的问题 仍然可以使用mapState而不使用名称空间,如下所示:
computed: {
...mapState({
todos: state => state.FilenameOfYourModule.todos
})
}
演示如何使用mapState和getter@Anatoly更新了我的问题能否将vuex相关代码共享为well@depperm加:)
computed: mapState({
todos: state => state.todos
})
computed: {
todos() {
return this.$store.state.{module_filename}.todos
}
}
computed: {
...mapState({
todos: state => state.FilenameOfYourModule.todos
})
}