0

Suppose I have this template in vue:

<p @click="handleParagraphClick">
    <span @click="handleSpanClick">Some text</span>
</p>

When I click on span I trigger also a paragraph click handler running. There is such checking for jquery to check if bubbling triggered a click:

$('#id_of_p').click(function(event) {
    if (event.target == this) {
        // event was triggered on the body
    }
});

When I use event.target within handleParagraphClick(event) I get reference to span element. How to get reference to paragraph to compare span event.target and paragraph this variable like in jquery?

Upd.

Template above is simplified version of my current code. I have nested components. Component with span is rendered inside paragraph component.

webprogrammer
  • 2,393
  • 3
  • 21
  • 27
  • What is it you want to do with the information if you can get it? If you want to make sure `handleParagraphClick` only executes for clicks on the `

    `, you can use `@click.self="handleParagraphClick"`

    – Phil Mar 11 '20 at 22:39
  • @Phil, I've forgotten about 'self' event modifier. So, yes it should help me with my question. Thank you! – webprogrammer Mar 12 '20 at 09:37

1 Answers1

1

You can use event.currentTarget to get the element with the click event on. For reference, I found the answer here.

It's probably not what you need, but in case you don't want to trigger handleParagraphClick when you click the span you can use @click.stop

new Vue({
  el: "#app",
  methods: {
    onPClick: function(ev) {
      console.log("Current Target: " + ev.currentTarget);
      console.log("Target: " + ev.target);
    }
  }
});
p {
  padding: 10px;
  background: red;
}

span {
  padding: 5px;
  background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <p @click="onPClick">
    P
    <span>
SPAN
</span>
  </p>

</div>
tony19
  • 125,647
  • 18
  • 229
  • 307
Shoejep
  • 4,414
  • 4
  • 22
  • 26
  • I see `currentTarget: null`. But I have nested components. Component with span is rendered inside paragraph component. Maybe this is the reason why `currentTarget` is null. – webprogrammer Mar 11 '20 at 22:17
  • Hmm okay, it works fine in the simple fiddle scenario. After doing some research there seems to be a few reasons it could be null, might be worth a try [vue-forum](https://forum.vuejs.org/t/currenttarget-return-null/16286), [GitHub](https://github.com/vuejs/vue/issues/6867) – Shoejep Mar 11 '20 at 22:41
  • `onPClick` might need to be `onPClick($event)` – blessing Mar 11 '20 at 22:41