在 Vue 3 中,defineEmits 用于在组件中定义自定义事件,使得子组件可以向父组件发送数据。以下是 defineEmits 的基本用法
<script setup>
const emits = defineEmits(['complexEvent']);
const handleEmit = () => {
emits('complexEvent', '这是子组件发送过来的数据');
};
</script>
<script setup>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
const message = ref('');
const complexEvent = (val) => {
message.value = val;
};
</script>
<template>
<div>{{ message }}</div>
<ChildComponent @complexEvent="complexEvent" />
</template>
ts 中使用
<ReImageVerify v-model:code="imgCode" />
interface Emits {
(e: "update:code", code: string): void
}
const emit = defineEmits<Emits>()
watch(imgCode, newValue => {
emit("update:code", newValue)
})