programing

Vuex mapState가 어레이가 아닌 개체를 반환합니까?

itsource 2022. 7. 27. 23:06
반응형

Vuex mapState가 어레이가 아닌 개체를 반환합니까?

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;
    }
};

Vuex 매뉴얼에 따르면mapStatehelper는 기본적으로 개체를 반환합니다.

getter가 객체 대신 배열을 반환하는 이유는 getter가 항상 함수여야 하기 때문입니다.당신의 경우, 단선 화살표 기능은state => state.todos는 오브젝트에 접속하여 암묵적으로 오브젝트 내의 스테이트를 반환합니다.

스트링 배열을 도우미에 전달하는 대신mapState(['todos'])를 열고 다음 문서에 표시된 추가 작업(개체에 액세스하기 위한 작업)을 수행할 수 있습니다.

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

기본적으로 getter와 같은 방법으로 상태에 액세스하고 있습니다.이번만 이 작업을 컴포넌트 내에서 수행합니다.computed부분.

주의: 네스트된 모듈이 있는 경우 다음 문서에 나와 있는 것처럼 네임스페이스를 바인드할 수 있습니다.

또한 여러 스토어 상태 속성이나 getter를 사용할 필요가 없는 경우 해당 싱글에 액세스할 수 있습니다.todos를 사용하는 속성this.$store숏컷:

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

도움이 됐으면 좋겠다.

모듈 이름을 지정하면 문제가 해결되었습니다. 이유는 잘 모르겠습니다.

모듈 이름을 지정하면 문제가 해결되었습니다. 이유는 잘 모르겠습니다.

모듈 상태가 아닌 액션, 돌연변이 및 getter만 글로벌 네임스페이스에 등록됩니다.검색 결과 네임스페이스로 문제가 해결되었습니다.

그래도 다음과 같이 네임스페이스 없이 mapState를 사용할 수 있습니다.

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

언급URL : https://stackoverflow.com/questions/61731289/vuex-mapstate-returns-object-not-array

반응형