Vue中动态组件的点击事件

7

我使用 v-for 渲染 Vue 组件:

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

点击渲染的组件不会触发myFunction方法。然而,点击手动插入的组件会触发:

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

如何纠正这个问题?
4个回答

12

添加 .native 修饰符以监听原生事件而非组件事件。

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

来源:https://v2.vuejs.org/v2/api/#v-on


1
你可以将点击处理程序作为属性传递给子组件,例如:
<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>

0

请尝试以下操作:

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

1
@click 绑定需要在 div 上,但除此之外这个代码是有效的。为什么呢?因为这会在 DOM 中创建不必要的元素。 - Mikko
@Mikko 我已经修改了答案,不应该在DOM中添加不必要的元素。 - Saurabh
将点击事件绑定到模板标签也不起作用。 - Mikko

0
我猜你试图做的事情是不必要或不正确的。如果你想在子组件被点击时调用在父组件中定义的函数,你可以将该组件包装在一个元素中,并将事件绑定到该包装器上。这样无论你点击哪个组件,该函数都会触发,而且你不需要直接将事件绑定到组件上。
<div class="wrapper" v-for="component in components" @click="myFunction(component.id)">
    <component :is="component.type"/>
</div>

应该可以了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接