• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    해결됨

스토어 모듈화 시 ...mapState

20.01.05 01:39 작성 조회수 576

4

안녕하세요? 좋은 강좌를 해주셔서 정말 감사합니다.

마지막 강의 수강 중 질문사항이 생겨 문의드립니다.

todoApp 으로 모듈화 하여 TodoHeader.vue에서 ...mapState 를 사용하여 'Todo it'를 가져오려 하는데 

this.$store.state.todoApp.headerText

으로는 가져오나

import { mapState } from 'vuex'

export default {
computed: {
...mapState (['headerText'])
}
}

이런 방식으로는 headerText가 undefined라고 표기됩니다.

...mapState(['todoApp/headerText']) 역시 같은 증상인데 어떻게 해야 될까요??

답변 4

·

답변을 작성해보세요.

3

cyzhzhd님의 프로필

cyzhzhd

2020.07.28

mapState('모듈 명') 을 이용하기 위해선, 모듈을 export할 때 namespaced: true, 옵션을 지정해줘야 하는 것 같습니다.

modules/todoApp.js

export default {
  namespaced: true,
  state,
  getters,
  mutations,
};

TodoHeader.vue

  computed: {
    ...mapState("todoApp", ["headerText"]),

이렇게 변경하고 나면 TodoList 등 helper함수를 이용한 다른 파일들도 위와 동일한 형식으로 변경해 주어야 합니다.

특히 TodoInput.vue에서

        // this.$store.commit("addOneItem", this.newTodoItem);

        this.addOneItem(this.newTodoItem);로 변경해 주어야 정상 작동합니다.

* 정확하지 않은 정보일 수 있습니다. 아니라면 댓글 달아주세요!

0

느루님의 프로필

느루

2022.03.17

저는 todoApp.js 모듈에 있는 headerText를 전달해주는 getters 함수를 하나 만들어서 전달하는 방식으로 해결했어요!
storedTodoItems() 로 todoItems를 전달해서 리스트를 뿌려준 것처럼요.

// todoApp.js
const state = {
  headerText: 'My TODO',
  todoList: storage.fetch(),
};

const getters = {
  getHeaderText(state) {
    return state.headerText;
  },
  storedTodoItems(state) {
    return state.todoList;
  },
};

// TodoHeader.vue
<template>
  <header>
    <h1>{{ this.headerText }}</h1>
  </header>
</template>

<script>
import { mapGetters } from 'vuex';
export default {
  computed: {
    ...mapGetters({
      headerText: 'getHeaderText',
    }),
  },
};
</script>

0

이은혜님의 프로필

이은혜

2021.01.28

저는 간단하게 todoApp.js 에서 적용한 

headerText : 'TODO it!',

이 부분을 store.js 에 적용했습니다.

export const store = new Vuex.Store({

  state: {

    headerText : 'TODO it!',

  },

그러면 다른 설정없이 제대로 보여지네요..!

0

안녕하세요 Aredra님, 먼저 좋은 강좌라고 말씀해주셔서 감사합니다 :)

질문 주신 mapState는 모듈화를 했을 때 아마 아래와 같은 패턴으로 접근될 것 같습니다.

...mapState('모듈 명', ['state 이름'])

자세한 내용은 아래 문서를 한번 참고해보세요 :)

https://vuex.vuejs.org/guide/modules.html

강의 수강해주셔서 감사합니다..!