Search code examples
javascriptvue.jsvuejs3

How would I capture dinamically events from child


If I need to transform this template:

<template v-if="props.componentType === 'GeButton'">
  <GeButton
    :button-props="componentData"
    @button-click="buttonClick(componentData)"
  />
</template>
<template v-else-if="props.componentType === 'SugerenciaGE'">
  <SugerenciaGE
    :item="componentData"
    estilos=""
    @sugerencia-clickada="buttonClick(componentData)"
  />
</template>

to this template:

<component
  :is="componentToRender.component"
  v-if="componentToRender.component"
  v-bind="{ data: componentData }" />

The events needs to be captured how? (Because each component has its own event names.) So the target is to captured them dynamically I know is using the directive v-on="{..eventName}" like:

<component
  :is="componentToRender.component"
  v-if="componentToRender.component"
  v-bind="{ data: componentData }"
  v-on="{ ...capturedEvent(componentData) }"
/>

But it's been called out of control every second that way.


Solution

  • I solved it just by renaming the prop of every child component in a object with the same prop name like so -> In a child component

    interface Props {
      estilos?: string
      data: IDetalleEstacion | INarrowDown
    }
    const props = withDefaults(defineProps<Props>(), {
      estilos: '',
    }
    

    another child component like so:

    const props = defineProps<{
      data: buttonProps
    }>()
    

    then in the parent component:

      <component
        :is="listToRender.component"
        v-if="listToRender.component"
        :="{ data: componentProps }"
        @item-click="buttonClick(componentProps)"
      />