I render Vue components using v-for:

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

Clicking on the rendered component doesn't fire the myFunction method. However, clicking a manually inserted component does:

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

How to correct this?

share|improve this question

Add the .native modifier to listen for a native event instead of a 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

share|improve this answer
    
This is working sir! – Iamzozo May 11 at 13:30

You can pass the click handler as a prop to the child component, for instance:

<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>
share|improve this answer

Try following:

<template v-for="component in components">
  <component :is="component.type" @click="myFunction(component.id)" />
</template > 
share|improve this answer
1  
The @click binding needs to be on the div but otherwise this works. Why is that? This creates unnecessary elements in the DOM. – Mikko Dec 12 '16 at 10:28
    
@Mikko I have modified the answer, which should not add unnecessary elements in the DOM. – Saurabh Dec 12 '16 at 11:07
    
Binding the click event to the template tag doesn't work either. – Mikko Dec 12 '16 at 11:12

I'm guessing that what you are trying to do is not needed or correct. If you want to call a function defined in the parent whenever the child component is clicked you can just wrap the component in an element and bind the event to that wrapper. That way the function will fire whenever you click whichever component is rendered inside it and you'll have not events bound directly to components

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

That should do it.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.