티스토리 뷰

대체 vue에서는 부모 컴포넌트의 함수를 어떻게 실행하는가...!!!!!

수많은 시행착오 끝에 알게 됐다.... 챗지피티가 data() 버전으로만 알려주거나 헛소리를 해서 한참 걸렸다.... 믿을게 못 되는 녀석.....

 

먼저 부모컴포넌트에서 전달할 함수를 @나 v-on:키워드를 사용해서 전달해 준다. 이유는 모르겠지만 ref를 사용해야 이벤트가 발생했을 때 값이 바뀌는 것 같아서 ref도 추가해 줬다. ref는 다음에 찾아볼 예정이다.

// 부모 컴포넌트
...
export default defineComponent({
  setup() {
    const isShowModal = ref(false);

    const showModal = () => {
      isShowModal.value = !isShowModal.value;
    };

    return { isShowModal, showModal };
  },
  components: {
    Main,
    WriteModal,
  },
});
</script>

<template>
  <Main @show-modal="showModal" />
  <div v-if="isShowModal">
    <WriteModal v-on:show-modal="showModal" />
  </div>
</template>

 

자식 컴포넌트에서 emits을 선언하고 넘겨준 이벤트 이름을 []에 넣는다.

setup()의 두번째 인자로는 setupContext를 받는데 여기서 emit 함수에 접근할 수 있다. 쓰기 편하도록 구조분해 할당을 해준다.

클릭하면 부모 컴포넌트 함수를 실행할 것이므로 클릭하면 실행할 함수를 선언하고 그 내부에 emit(호출할 이벤트)를 넣어서 부모 컴포넌트 함수가 실행되도록 한다. emit()의 2번째 인자로 값을 넣어서 값을 변경할 수도 있다고 한다.

// 자식 컴포넌트 1
<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'WriteModal',
  emits: ['show-modal'],
  setup(_, { emit }) {
    const clickHideModalBtn = () => {
      emit('show-modal');
    };

    return { clickHideModalBtn };
  },
});
</script>

<template>
  <div class="background">
    <div class="write-modal">
      <button class="close-btn" @click="clickHideModalBtn">
        <span
          class="pi pi-times icon"
          style="font-size: 1.2rem; color: #000"
        ></span>
      </button>
    </div>
  </div>
</template>

 

// 자식 컴포넌트 2
...
export default defineComponent({
  name: 'Main',
  components: {
    WriteBtn,
  },
  emits: ['show-modal'],
  setup(_, { emit }) {

    const clickShowModalBtn = () => {
      emit('show-modal');
    };

    return { clickShowModalBtn };
  },
});
</script>

<template>
  <div class="container">
    <WriteBtn @click="clickShowModalBtn" />
  </div>
</template>
728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함