Vue3.2 新特性 --- 自定义事件(defineEmits)

11,501 阅读1分钟

在 <script setup> 中 声明 emit ,必须使用 defineEmits API,这是一个宏命令,不需要导入,直接可在 <script setup> 使用且只能在 <script setup> 中使用

  1. 运行时声明
// 父组件
<Info @parentClick="parentClick" @parentChang="parentChang"></Info>

<script setup>
    // 这样是没有任何的类型检查的 不管是什么值都可以传递过来
    const parentClick = (data: number) => { alert('子组件触发了此事件,传递的值是' + data) }
    const parentChang = () => { alert('子组件触发了此事件') }
</script>

// 子组件
<button @click="handClick">点击触发handClick事件</button>
<input type="checkbox" @change="handChang">

<script setup>
    const emits = defineEmits(['parentClick','parentChang']) // 语法糖
    
    const handClick = () => {
        emits('parentClick',2) // 使用方式和 vue2 this.$emit 一样
    }
    const handChang = () => {
        emits('parentChang') // 使用方式和 vue2 this.$emit 一样
    }
</script>

2 . 类型声明式

   // 子组件
   <script setup>
    const emits = defineEmits<{
        (e: 'parentClick', data: number): void // 函数类型 当传递的值的类型不是number时会报错
        (e: 'parentChang'): void // 函数类型
    }>();
    
    const handClick = () => {
        emits('parentClick',2) // 使用方式和 vue2 this.$emit 一样
    }
    const handChang = () => {
        emits('parentChang') // 使用方式和 vue2 this.$emit 一样
    }
</script>

运行时声明和类型声明式同样不可同时使用

t.csdn.cn/3r75c 引用自此文章