概论
defineEmits 用来定义子组件暴漏给父组件的自定义事件
测试代码
- 子组件
<template>
<div class="box">child</div>
</template>
<script lang="ts" setup>
interface Emit {
(e: "emitfn1", data: Array<number>): void;
(e: "emitfn2", data: string): void;
}
const emit = defineEmits<Emit>();
emit("emitfn1", [234, 234]);
emit("emitfn2", "child_emit_data");
</script>
<style lang="stylus" scoped></style>
- 父组件
<template>
<div class="box">
<div>
<child @emitfn1="getChildFn" @emitfn2="getChildFn2" />
</div>
</div>
</template>
<script lang="ts" setup>
import child from "./components/child.vue";
//可以接收到子组件触发的事件
function getChildFn(data: Array<number>) {
console.log(data, "child_emit_data");
}
const getChildFn2 = (data: string) => {
console.log(data, "child_emit_data2");
};
</script>
<style lang="stylus" scoped></style>
前端工程师、程序员