最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dynamic component click event in Vue - Stack Overflow

programmeradmin0浏览0评论

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?

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 asked Dec 12, 2016 at 9:41 MikkoMikko 6372 gold badges10 silver badges22 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 12

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.

发布评论

评论列表(0)

  1. 暂无评论