컴포넌트는 내장 메서드 $emit
을 사용하여 템플릿 표현식(예: v-on 핸들러에서)에서 직접 사용자 정의 이벤트를 발신할 수 있다.
<!-- 자식 Component -->
<button @click="$emit('someEvent')">클릭</button>
<!-- 부모 Component -->
<MyComponent @some-event="callback" />
참고로 camelCase 형식으로 이벤트를 발신했지만, 부모에서 kebab-case 표기로 리스너를 사용하여 이를 수신할 수 있다.
✨ 예제 1
<template>
<div>
<button @click="$emit('createPost'"></button> <!-- 자식에서 부모로 이벤트 'createPost'내보내기 -->
</div>
</template>
<!-- TheView.vue 부모 컴포넌트 -->
<template>
<div>
<PostCreate @create-post="callFunction" ></PostCreate> <!-- 부모에서 이벤트 수신 -->
</div>
</template>
<script>
const callFunction = () => {
console.log('이벤트 수신');
}
</scritp>
(1) 버튼 클릭 이벤트 발생 $emit('createPost') 실행
(2) 자식 -> 부모 'createPost' 이벤트 내보냄
(3) 부모에서 @create-post로 이벤트 수신하고 callFunction 함수 실행
(4) 콘솔창에 '이벤트 수신' 출력됨.
이벤트와 함께 특정 값을 내보낼 수 있다.
$emit 함수 이벤트명에 추가로 파라미터를 넘길 수 있다.
✨ 예제 2
<!-- PostCreate.vue 자식 컴포넌트 -->
<template>
<div>
<button @click="$emit('createPost', '토끼는', '개발개발'"></button> <!-- 자식에서 부모로 이벤트 'createPost'내보내기 -->
</div>
</template>
<!-- TheView.vue 부모 컴포넌트 -->
<template>
<div>
<PostCreate @create-post="callFunction" ></PostCreate> <!-- 부모에서 이벤트 수신 -->
</div>
</template>
<script>
const callFunction = (word1, word2) => {
console.log(word1, word2); // 토끼는 개발개발 출력
}
</scritp>
예제2처럼 컴포넌트 내장메서드 $emit을 사용할 수도 있고,
setup함수의 context.emit을 사용하여 스크립트에서 처리할 수도 있다.
<script>
export default{
setup(props, {emit}){ //context.emit 구조분해할당
const createPost = () => {
emit('createPost', '토끼는', '개발개발');
}
return { createPost};
}
}
</scritp>