emit

    TIP

    子组件:(1)契机:一个点击事件;(2)先声明emit,const emit = defineEmits<{ (e: string, v: 传递的数据的类型): void }>();(3)然后在方法内通过 emit('自定义事件名','数据') 传递数据;

    父组件:子组件标签绑定自定义事件,自定义事件触发的方法的形参就是子组件传递的数据;

    注意:和 defineProps 一样, defineEmits 也无需引入就可以自动地在 <script setup> 中可用。

    1<template>
    2  <h2>子组件</h2>
    3  <button @click="send">发送</button>
    4</template>
    5
    6<script lang="ts" name="ChildComp" setup>
    7const emit = defineEmits<{ (e: string, v: string): void }>()
    8
    9let send = () => {
    10  emit('ChildData', 'child data')
    11}
    12</script>
    1<template>
    2  <h2>父组件</h2>
    3  <hr/>
    4  <child-comp @childData="getChildData"/>
    5</template>
    6
    7<script lang="ts" name="ParentComp" setup>
    8import ChildComp from "@/components/ChildComp.vue";
    9
    10const getChildData = (value) => {
    11  console.log(value)
    12}
    13</script>

    :::

    1/* 子组件 */
    2<template>
    3  <h2>子组件</h2>
    4  <button @click="send">发送</button>
    5</template>
    6
    7<script lang="ts" setup>
    8// 范型指定emit的参数
    9const emit = defineEmits<{ (e: string, v: string): void }>()
    10
    11const send = () => {
    12  // 自定义事件名,发送的内容
    13  emit('receive', '小苏同学')
    14}
    15</script>
    16
    17/* 父组件 */
    18<template>
    19  <h2>父组件</h2>
    20  <hr />
    21  <Child @receive="getChildData"></Child>
    22</template>
    23
    24<script lang="ts" setup>
    25import Child from './ChildView.vue'
    26
    27// 自定义事件方法的形参就是子组件传递的数据
    28const getChildData = (v: string) => {
    29  console.log(v)
    30}
    31</script>