defineEmits 实现父子组件通信
-
父组件绑定事件:
@increase="handleIncrease"
-
父组件回调函数:
const handleIncrease = (num: number) => {}
-
子组件定义
emit
:
// ts 专有
const emit= defineEmits<{
(e: 'increase', num: number): void
}>()
- 子组件调用
emit
emits('increase', 1);
父组件
<template>
<section class="parent">
<childVue :num="nums" @increase="handleIncrease"></childVue>
</section>
</template>
<script setup>
import childVue from './child.vue';
import { ref } from 'vue';
const nums = ref(0);
// 回调函数
const handleIncrease = (num: number) => {
nums.value += num;
};
</script>
子组件
<template>
<section class="box" @click="handelClick">{{ num }}</section>
</template>
<script setup>
// ts 专有
const emit= defineEmits<{
(e: 'increase', num: number): void
}>()
const handelClick = () => {
emits('increase', 1);
};
</script>