useEmitAsProps
将 emits 转换为类似于 props 的对象。
当您为组件构建包装器时,最大的痛点之一是转发组件发出的所有事件。
通过使用这个组合式函数,它将您声明的 emits 转换为一个 Vue 组件可接受的事件处理程序对象。 它的作用是将组件的 emit 事件转换成标准的 onXxx 形式,从而能以 props 的形式传递下去,适用于高阶组件(HOC)或中间组件需要 事件透传 的场景。
使用场景
Vue 3 没有内建事件透传机制,所以父组件传入的 @xxx 无法自动绑定到子组件的 emit('xxx') 上,尤其是:
- 你在中间层组件想让事件继续暴露给外部使用时
- 封装库组件并想向下兼容使用原生的
onClick、onChange等
假设你有一个中间层组件 MyWrapper.vue
<script setup lang="ts">
import { useEmitAsProps } from './useEmitAsProps'
const props = defineProps()
const emit = defineEmits(['update:modelValue', 'change'])
const emitProps = useEmitAsProps(emit)
</script>
<template>
<InnerComponent v-bind="props" v-bind="emitProps" />
</template>
这样
InnerComponent 中如果调用 emit('update:modelValue', val),你在最外层就可以用 @update:modelValue="..." 响应。用法
<script setup lang="ts">
import { useEmitAsProps } from 'reka-ui'
const emits = defineEmits<CompEmitType>()
const emitsAsProps = useEmitAsProps(emits)
</script>
<template>
<Comp v-bind="emitsAsProps">
...
</Comp>
</template>