
ตัวอย่างการใช้ Emits เพื่อส่ง event ใน component ไปยัง parent
มาดูตัวอย่างการใช้ Emits เพื่อส่ง event ใน component ไปยัง parent กัน
ในการเขียน component บางครั้ง เราอาจจะต้องการส่งค่า หรือส่ง event บางอย่างส่งไปให้ parent ที่เรียกใช้ เราสามารถใช้ emits ได้ ตามตัวอย่าง
<script setup>
// declare emitted events
const emit = defineEmits(['response'])
// emit with argument
emit('response', 'hello from child')
</script>
จากโค้ดใน emit() พารามิเตอร์แรก จะเป็นชื่อที่เราส่งกลับไปให้ parent และพารามิเตอร์ตัวที่สองเป็นค่าหรือ event ที่ส่งกลับไป
ใน parent เราก็จะเรียกใช้ได้ โดยใช้ v-on ตามตัวอย่างนี้
<ChildComp @response="(msg) => childMsg = msg" />
ตัวอย่างแบบเต็ม
ตัวอย่างโค้ดใน component
<script setup>
const emit = defineEmits(['response'])
emit('response', 'hello from child')
</script>
<template>
<h2>Child component</h2>
</template>
ส่วนใน parent ที่เราเรียกใช้ ก็จะเป็นประมาณนี้
<script setup>
import { ref } from 'vue'
import ChildComp from './ChildComp.vue'
const childMsg = ref('No child msg yet')
</script>
<template>
<ChildComp @response="(msg) => childMsg = msg" />
<p>{{ childMsg }}</p>
</template>