[英]Dynamic component click event in Vue
我使用v-for
渲染 Vue 組件:
<component
v-for="component in components"
:is="component.type"
@click="myFunction(component.id)">
</component>
單擊呈現的組件不會觸發myFunction
方法。 但是,單擊手動插入的組件會:
<div @click="myFunction('...')"></div>
如何糾正這個?
添加 .native 修飾符以偵聽本機事件而不是組件事件。
<component
v-for="component in components"
:is="component.type"
@click.native="myFunction(component.id)">
</component>
來源: https ://v2.vuejs.org/v2/api/#v-on
您可以將點擊處理程序作為道具傳遞給子組件,例如:
<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>
嘗試以下操作:
<template v-for="component in components">
<component :is="component.type" @click="myFunction(component.id)" />
</template >
我猜您不需要或不正確。 如果您想在單擊子組件時調用父組件中定義的函數,您可以將組件包裝在一個元素中並將事件綁定到該包裝器。 這樣,只要您單擊其中呈現的任何組件,該函數就會觸發,並且您不會將事件直接綁定到組件
<div class="wrapper" v-for="component in components" @click="myFunction(component.id)">
<component :is="component.type"/>
</div>
那應該這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.