음악, 삶, 개발
자식과 부모의 대화 : emit 과 v-on 본문
우리는 앞서 socket io 를 통해 emit 을 배웠었다.
보내는쪽이,
emit('event명', '보낼 메세지')
를 하게되면,
어딘가에서 이 메세지를
on('event명', 실행할함수명)
으로 받아, 원하는 함수를 실행하였었다.
< 자식이 부모에게 메세지 보내기 >
socket io 와 유사한 방식으로,
자식이 특정 event 명을 사용하여 이벤트를 보낼수있다.
먼저 setup 함수의 2번째 인자인 context 가 필요하며,
이 context 의 메소드로 emit 이 존재한다.
아래와 같이 자식 component 를 작성한다.
<!-- Child.vue -->
<template>
<button @click="doSomething">I'm a child.</button>
</template>
<script>
export default {
setup(props, context) {
function doSomething() {
// childEvent 하면 에러남. child-event 여야함.
context.emit('child-event', 'event from child!')
}
return { doSomething }
}
}
</script>
이제 자식 Component 는 'child-event' 라는 event 명을 사용하여 메세지를 쏘개된다.
그럼 이를 부모 컴포넌트가 수신할때는 v-on:이벤트명 지시어를 사용한다.
<!-- Parent -->
<template>
<div>I'm a parent</div>
<child v-on:child-event="eventFromChild" />
</template>
<script>
import Child from './Child.vue'
export default {
components : { Child },
setup() {
function eventFromChild(message) {
console.log(message)
}
return { eventFromChild }
}
}
</script>
< 부모가 자식에게 메세지 보내기 >
부모가 자식에게 메세지를 보낼때는, props 를 사용해야한다.