简体   繁体   English

Vue中的动态组件点击事件

[英]Dynamic component click event in Vue

I render Vue components using v-for :我使用v-for渲染 Vue 组件:

<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.单击呈现的组件不会触发myFunction方法。 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.添加 .native 修饰符以侦听本机事件而不是组件事件。

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

Source: https://v2.vuejs.org/v2/api/#v-on来源: 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.那应该这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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