子组件向父组件传递消息(Events)
子组件可以通过 $emit
触发事件,父组件可以监听这些事件并作出响应。
子组件:
<template>
<button @click="sendMessage">Send Message to Parent</button>
</template>
<script lang="ts" setup>
const emit = defineEmits(['message']);
function sendMessage() {
emit('message', 'Hello from Child!');
}
</script>
父组件:
<template>
<div>
<ChildComponent @message="handleMessage" />
</div>
</template>
<script lang="ts" setup>
import ChildComponent from './ChildComponent.vue';
function handleMessage(message: string) {
console.log(message);
}
</script>