emit 자식 → 부모로 이벤트 전달자식 컴포넌트가 부모에게 이벤트나 데이터를 전달할 때 사용
<!-- Parent.vue -->
<ChildComponent @clicked="handleClick" />
<script setup>
import ChildComponent from './ChildComponent.vue'
const handleClick = (msg) => {
console.log('테스트:', msg)
}
</script>
<!-- ChildComponent.vue -->
<template>
<button @click="sendMessage">클릭</button>
</template>
<script setup>
const emit = defineEmits(['clicked'])
const sendMessage = () => {
emit('clicked', '클릭 이벤트 실행')
}
</script>
결과: 버튼을 클릭하면 부모 콘솔에 "클릭 이벤트 실행" 출력
React에는 emit이 없고 부모가 콜백 함수를 props로 내려주고 자식이 해당 함수를 호출
// Parent.tsx
import Child from './Child'
export default function Parent() {
const handleClick = (msg) => {
console.log('테스트:', msg)
}
return <Child onClickButton={handleClick} />
}
// Child.tsx
export default function Child({ onClickButton }) {
return <button onClick={() => onClickButton('클릭 이벤트 실행')}>클릭</button>
}
slot 부모 → 자식으로 콘텐츠 전달slot은 부모가 자식 컴포넌트 내부에 콘텐츠를 꽂아 넣는 개념 (React의 children)
<!-- Parent.vue -->
<Layout>
<p>slot 테스트</p>
</Layout>
<!-- Layout.vue -->
<template>
<div class="layout">
<header>header</header>
<slot /> <!-- 부모의 콘텐츠가 들어오는 자리 -->
<footer>footer</footer>
</div>
</template>
결과:
header
slot 테스트
footer
// Parent.tsx
import Layout from './Layout'
export default function Parent() {
return (
<Layout>
<p>slot 테스트</p>
</Layout>
)
}
// Layout.tsx
export default function Layout({ children }) {
return (
<div className="layout">
<header>header</header>
<main>{children}</main>
<footer>footer</footer>
</div>
)
}
emit: 자식 → 부모에게 신호를 보냄
slot: 부모가 자식 내부를 채우는 공간 부모 → 자식에게 값을 채움