How to prevent/stop click propagation in vuejs

2019-07-14 11:25发布

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

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"

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>

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?

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-14 12:13

You can stop propogation using the .stop event modifier as:

@click.stop="sayHello"

Now the event won't be propagated to the parent

More on the list of event modifiers: https://vuejs.org/v2/guide/events.html#Event-Modifiers

查看更多
登录 后发表回答