如何在vue3组合式函数中使用emit

发布时间:2023-09-05浏览次数:1058 次
关于Vue3的组合式函数,简单来说就是,如果我们在多个组件中,都用到一些共同的功能时就可以将其封装为一个组合式函数。类似于Vue2中的minix。但是在Vue3

关于Vue3的组合式函数,简单来说就是,如果我们在多个组件中,都用到一些共同的功能时就可以将其封装为一个组合式函数。类似于Vue2中的minix。但是在Vue3的组合式函数中,如果我们要使用emit获取父组件传递的事件时,以往写在script setup中的defineEmits就不能用了,控制台会提示:defineEmits() is a compiler-hint helper that is only usable inside <script setup> of a single file component. Its arguments should be compiled away and passing it at runtime has no effect.

那么此时,我们就不能再继续使用defineEmits了。

一、通过getCurrentInstance方法实现

Vue3中,也为我们准备了响应的组件:getCurrentInstance,通过getCurrentInstance我们可以获取当前正在调用该组合式函数的组件实例,然后通过ctx.emit来访问父组件身上的方法。

即,之前的:

emits('event');

要改成:

import {getCurrentInstance} from "vue";
const instance = getCurrentInstance();
instance.emit('event')

通过这样的方式,我们就可以拿到调用该组合式函数的组件,并通过ctx.emit的方式访问到其父组件身上的方法。

二、通过向组合式函数传参实现

当然,还有一种方式,就是直接将 emits做为参数,传递给组合式函数去使用。即在调用组合式函数的组件中,先使用defineEmits声明好emits,再将emits做为参数传递给组合式函数。

const emits = defineEmits(['event'])
const {...} = useForm(emits)

三、通过向方法传参实现

在调用方法时,通过向方法传参实现

 @click="event(emits,data)"

大家根据自己的实际代码情况,选择使用。

扫一扫,在手机上查看