如何在 vuejs 中防止/停止点击传播 [英] How to prevent/stop click propagation in vuejs
问题描述
我有一个递归列表(树),每个元素都有一个 @click="sayHello(el.id)"
.现在的问题是,因为它是一个嵌套列表,如:
I have a recursive list (tree) and each element has a @click="sayHello(el.id)"
. Now the problem is, since it is a nested list like:
list-element-0-01
├──list-el-1-01
│ └──list-el-2-01
└──list-el-1-02
└──list-el-2-02
如果我点击元素:list-el-2-01
然后我得到
If I click the element: list-el-2-01
then I get the output of
> "list-el-2-01"
> "list-el-1-01"
> "list-el-0-01"
完全按照这个顺序.我的意思是我明白了,看着 html:
In exact that order. I mean I get it, looking at the html:
<ul>
<li @click="sayHello('list-el-0-01')"> one-one
<ul>
<li @click="sayHello('list-el-1-01')"> two-one
<ul>
<li @click="sayHello('list-el-2-01')"> three-one </li> // I click this
</ul>
</li>
<li @click="sayHello('list-el-1-02')"> two-two
<ul>
<li @click="sayHello('list-el-2-02')"> three-two </li>
</ul>
</li>
</ul>
</li>
</ul>
不知何故,我还单击了所有包装元素,这是有道理的.我的问题 - 有没有办法只让 exact 元素触发它的点击事件?
It makes sense that I am also clicking all the wrapping elements, somehow. My question - is there a way to only have the exact element fire it's click event?
推荐答案
您可以使用 .stop
事件修饰符停止传播:
You can stop propogation using the .stop
event modifier as:
@click.stop="sayHello"
现在事件不会传播到父级
Now the event won't be propagated to the parent
关于事件修饰符列表的更多信息:https://vuejs.org/v2/guide/events.html#Event-Modifiers
More on the list of event modifiers: https://vuejs.org/v2/guide/events.html#Event-Modifiers
这篇关于如何在 vuejs 中防止/停止点击传播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!