• 카테고리

    질문 & 답변
  • 세부 분야

    프론트엔드

  • 해결 여부

    미해결

TodoInput컴포넌트의 addTodo 헬퍼함수 적용 질문드립니다.

23.11.06 16:24 작성 23.11.06 17:20 수정 조회수 174

1

<template>
  <div class="inputBox shadow">
    <input type="text" v-model="inputValue" v-on:keyup.enter="checkAndAddTodo()">
    <span class="addContainer" v-on:click="checkAndAddTodo()">
...
</template>

<script>
  methods: {
    ...mapMutations([
      'addTodo'
    ]),

    checkAndAddTodo() {
      if (!this.checkEmpty()) {
        this.addTodo(this.inputValue);
        this.clearInput();
      } else {
        this.showModal = !this.showModal;
      }
    },
    checkEmpty() {
      console.log("inputValue: ", this.inputValue)
      if(this.inputValue === '') {
        return true;
      }
      return false;
    },
    clearInput() {
      this.inputValue = '';
    }
  },
  components: {
    Modal: Modal
  }
</script>

addTodo도 helper 함수를 적용해서 변경해보려 했는데..
이런식으로 변경하는게 맞을까요??

checkAndAddTodo함수 내의 this.addTodo() 실행시 mapMutations의 'addTodo'를 따라 store까지 전달이 되긴 하는데.. 올바른 방식으로 수정한건지 궁금합니다

답변 2

·

답변을 작성해보세요.

0

안녕하세요, 제가 답이 좀 늦었네요 🙂 네 괜찮은 것 같아요. 템플릿 표현식에서 메서드 연결하시는 부분만 v-on:click="checkAndAddTodo"

요 형태로 해주시면 좋겠네요 :)

0

인프런 AI 인턴님의 프로필

인프런 AI 인턴

2023.11.08

안녕하세요, dev_climber 님. addTodo 함수를 helper 함수로 변경하려는 질문을 주셨네요.

제시해주신 코드에서 addTodo 함수는 Vuex의 mapMutations를 사용하여 뮤테이션을 실행하고 있습니다. 이 경우, Vuex에서 state를 변경하는 동작을 수행하게 됩니다.

addTodo 함수를 helper 함수로 변경하기 위해서는 Vuex의 mapMutations 대신 mapActions를 사용해야 합니다. mapActions는 액션을 컴포넌트에서 실행할 수 있도록 매핑해주는 도우미 함수입니다.

아래는 addTodo를 helper 함수로 변경한 예시입니다.

<template>
  <!-- 생략 -->
</template>

<script>
  methods: {
    ...mapActions([
      'addTodo'
    ]),

    checkAndAddTodo() {
      if (!this.checkEmpty()) {
        this.addTodoHelper(this.inputValue);
        this.clearInput();
      } else {
        this.showModal = !this.showModal;
      }
    },
    addTodoHelper(todo) {
      this.addTodo(todo);
    },
    checkEmpty() {
      // 생략
    },
    clearInput() {
      // 생략
    }
  },
  // 생략
</script>

위 코드에서 addTodo 함수를 addTodoHelper로 변경하여 Vuex의 액션을 실행하고 있습니다. 실제 동작은 기존과 동일하게 이루어지며, 액션 내에서 상태를 변경하게 됩니다.

이를 통해 addTodo를 헬퍼 함수로 변경할 수 있습니다. 정확한 코드 수정은 다양한 요구사항에 따라 다를 수 있으므로, 필요에 따라 추가적인 수정을 진행하시면 됩니다. 감사합니다!