简体   繁体   中英

Dynamic component click event in Vue

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?

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

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>

Try following:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM