Vuex mapState返回对象而不是数组?

问题描述 投票:0回答:1

我想用v-for在一个对象数组上循环。然而,我的状态返回的对象中包含了一个Objects数组,这导致v-for无法工作。

{ "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'])
    }

使用getter:

<template>
    <div class="content-center">
       {{getTodos}}   
    </div>
</template>
....
import {mapActions, mapGetters, mapState} from 'vuex';

 export default {
        ....
        computed: mapGetters(['getTodos'])
    }

我还想补充一下,我使用的是模块,如果这对调用mapState有什么影响的话。

vuex。

const state = {
    todos: []
};

const getters = {

    getTodos: state => state.todos

};

const actions = {
    loadTodos({commit}) {
        axios.get('/api/todos', {
        }).then(response => {
            commit('setTodos', response.data);
        }).catch(error => {
            console.error(error);
        })
    }
};

const mutations = {
    setTodos: (state, response) => {
        state.todos = response;
    }
};
vue.js vuex
1个回答
0
投票

让我的模块按名字间隔排列,解决了这个问题,尽管我不太清楚为什么。


0
投票

根据 Vuex文件జజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజ mapState helper默认返回一个对象。

之所以你的getter返回一个数组而不是一个对象,是因为getter必须始终是一个函数。在您的例子中,单行箭头函数 state => state.todos 访问对象,然后它隐式地返回对象中的状态。

而不是像这样将一个字符串数组传递给帮助程序 mapState(['todos'])您可以打开它来执行额外的操作(即访问对象),如图所示。文件:

computed: mapState({
        todos: state => state.todos
})

请注意,你基本上是以与getter相同的方式访问状态... ... 只不过这次是在组件中的 computed 节。

: 如果你有嵌套的模块,你可能会想要绑定你的命名空间,如在 这里的文档.

此外,如果你不需要使用多个存储状态属性或获取器,那么你可以只访问那个单一的 todos 属性,使用 this.$store 捷径。

computed: {
    todos() {
      return this.$store.state.{module_filename}.todos
    }
}

希望能帮到你

© www.soinside.com 2019 - 2024. All rights reserved.