Reputation: 637
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?
Upvotes: 8
Views: 15278
Reputation: 121
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://v2.vuejs.org/v2/api/#v-on
Upvotes: 12
Reputation: 1325
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.
Upvotes: 0
Reputation: 73589
Try following:
<template v-for="component in components">
<component :is="component.type" @click="myFunction(component.id)" />
</template >
Upvotes: 0
Reputation: 3663
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>
Upvotes: 1