我使用以下代码段来呈现列表:
<div @click.prevent="myhandler($event)"><!-- Delegated event handler-->
<div class="tasks" v-for="(task, subName) in step.tasks">
<button type="button">
{{ task.caption }}
</button>
<span> {{ task.callableName }} </span>
</div>
</div>
methods: {
myhandler(e){
// Event target may be a button element.
let target = e.target;
// …
// Let's assume we know 'target' is a button element instance.
// I wish I could have access to the v-for item ("task") which is associated in some ways to the button that was clicked.
// let the_task_reference = ?;
}…
是否有一种干净的方式,以便我可以达到与该按钮相关的v-for
范围特定任务?
谢谢。
答案 0 :(得分:0)
最直接的解决方案是将事件处理程序放在与div
指令相同的v-for
上,然后传入task
变量:
<div
class="tasks"
v-for="(task, subName) in step.tasks"
@click.prevent="myhandler(task, $event)"
>
<button type="button">{{ task.caption }}</button>
<span>{{ task.callableName }}</span>
</div>
如果您确实需要在父元素上使用事件处理程序,则可以通过组件属性跟踪单击的任务,并使用v-for
指令向div添加额外的单击处理程序:
<div @click.prevent="myhandler($event)"
<div
class="tasks"
v-for="(task, subName) in step.tasks"
@click="clickedTask = task"
>
<button type="button">{{ task.caption }}</button>
<span>{{ task.callableName }}</span>
</div>
</div>
您需要添加clickedTask
属性:
data() {
return {
clickedTask: null,
}
}
然后在处理程序中,您可以通过this.clickedTask
引用该任务。