Dynamic Component Click Event in Vue

I process Vue components with v-for:

<component
    v-for="component in components"
    :is="component.type"
    @click="myFunction(component.id)">
</component>

Clicking on the processed component does not start the method myFunction. However, clicking on a manually inserted component:

<div @click="myFunction('...')"></div>

How to fix it?

+4
source share
4 answers

Add a .native modifier to listen for the native event instead of the component event.

<component
    v-for="component in components"
    :is="component.type"
    @click.native="myFunction(component.id)">
</component>

Source: https://vuejs.org/v2/api/#v-on

+3
source

Try the following:

<template v-for="component in components">
  <component :is="component.type" @click="myFunction(component.id)" />
</template > 
0
source

, :

<component
   v-for="component in components"
   :is="component.type"
   :on-click="myFunction.bind(this, component.id)">
</component>

// Component
<template>
  <button @click="onClick">Click me</button>
</template>
<script>
  export default {
    props: ['onClick']
  }
</script>
0

I assume that what you are trying to do is not necessary or not right. If you want to call the function defined in the parent element each time the child component is clicked, you can simply wrap the component in the element and associate the event with this wrapper. Thus, the function will fire whenever you click whichever component is displayed inside it, and you will not have events related directly to the components

<div class="wrapper" v-for="component in components" @click="myFunction(component.id)">
    <component :is="component.type"/>
</div>

That should do it.

0
source

Source: https://habr.com/ru/post/1663498/


All Articles