1) 이벤트 발생 및 수신
컴포넌트의 <template> 블록 안에서 내장 함수 $emit()을 사용하여 직접 커스텀한 이벤트를 내보낼 수 있습니다.
<template>
<button @click="$emit('someEvent')">버튼</button>
</template>
그러면 부모 컴포넌트에서 v-on(또는 @)을 사용하여 이벤트를 수신할 수 있습니다.
<MyComponent @some-event="callFunction" />
2) 이벤트 파라미터
이벤트와 함께 특정 값을 내보낼 수 있습니다. $emit 함수 이벤트명에 추가로 파라미터를 넘길 수 있습니다.
<template>
<button @click="$emit('someEvent', 'Hello', 'World', '!')">버튼</button>
</template>
그런다음 부모 컴포넌트에서 이벤트와 함께 파라미터를 받을 수 있습니다.
<template>
<MyComponent @some-event="callFunction" />
</template>
<script setup>
export default {
setup() {
const callFunction = (word1, word2, word3) => {
alert(word1, word2, word3);
};
return {
callFunction
}
}
}
</script>
3) 이벤트 선언하기
문자열 배열 선언
export default {
emits: ['someEvent'],
setup(props, context) {
context.emit('someEvent', 'Hello World!')
}
}
객체문법 선언
export default {
emits: {
// 유효성 검사가 없는 이벤트 선언
someEvent: null,
// 유효성 검사가 있는 이벤트 선언
someSubmit: (result) => {
if (email && password) {
return true
} else {
console.warn('result 값이 비어있습니다!')
return false
}
}
},
setup(props, context) {
context.emit('someEvent', 'Hello World!')
}
}
4) v-model 만들기
<template>
<label>
{{ label }}
<input
type="text"
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
/>
</label>
</template>
<script>
export default {
props: ['modelValue', 'label'],
emits: ['update:modelValue'],
};
</script>
5) 다중 v-model 바인딩
<BookComponent
v-model:title="bookTitle"
v-model:author="bookAuthor"
/>
<template>
<article>
<strong>도서명</strong> :
<input
type="text"
:value="title"
@input="$emit('update:title', $event.target.value)"
/>
<br />
<strong>저자</strong> :
<input
type="text"
:value="author"
@input="$emit('update:author', $event.target.value)"
/>
</article>
</template>
<script>
export default {
props: ['title', 'author'],
emits: ['update:title', 'update:author'],
};
</script>'개발이 좋아서 > Vue가 좋아서' 카테고리의 다른 글
| 16장 Slots (0) | 2023.09.14 |
|---|---|
| 15장 Non-Prop 속성 (fallthrough 속성) (0) | 2023.09.14 |
| 13장 Props (0) | 2023.09.14 |
| 12장 Watch, WatchEffect (0) | 2023.09.14 |
| 11장 양방향 바인딩(v-model) (0) | 2023.09.14 |