📌 custom event
자식 컴포넌트가 부모 컴포넌트가 가진 데이터를 바꾸고 싶다면 부모에게 메시지를 줘야 한다.
부모는 그 메시지를 수신하면 데이터를 변경하는 코드를 실행한다.
이걸 custom event 라고 한다.
1. 자식은 $emit(작명, 전달할 자료) // 전달한 자료는 선택사항. 작명은 필수 => 커스텀 이벤트 전송
2. 부모는 @작명="데이터 변경하는 JS 코드"
3. 부모 컴포넌트가 전달한 자료를 사용할 때는 $event 로 사용 가능
자식 컴포넌트에서 openModal 이라는 커스텀 이벤트 전송, prodData의 id 값을 전송
//자식 컴포넌트
<h4 @click="$emit('openModal', prodData.id)">{{prodData.title}}</h4>
부모 컴포넌트에서 @openModal 로 커스텀이벤트를 받고, prodId라는 데이터에 자식 컴포넌트에게 받은 값을 저장
// 부모 컴포넌트
<Card @openModal="isModal = true; prodId = $event" v-for="(prodData,i) in prodList" :key="i" :prodData="prodData" :count="count[i]"/>
자식 컴포넌트의 클릭 이벤트 실행 내용을 함수로 만들 수 있다.
methods 에 등록하면 되는데 이때,
$emit -> this.$emit 으로 하는 것을 주의하기
마찬가지로 prodData.id -> this.prodData.id
// 자식 컴포넌트
methods : {
openModal() {
this.$emit('openModal', this.prodData.id)
}
}
'Vue3 > 코딩애플 part1' 카테고리의 다른 글
[Vue/코딩애플/part1] 11. UI 애니메이션 효과 주기 / transition (0) | 2024.07.30 |
---|---|
[Vue/코딩애플/part1] 10. input (v-model), watcher (0) | 2024.07.29 |
[Vue/코딩애플/part1] 8. props (0) | 2024.07.29 |
[Vue/코딩애플/part1] 7. 컴포넌트(Component) / 컴포넌트 파일명 한 단어로 가능하게 하는 방법 (0) | 2024.07.29 |
[Vue/코딩애플/part1] 6. 모달창에 상세 페이지 만들기 / v-if, v-else, v-else-if 문 (0) | 2024.07.29 |