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.

2
  • 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 <p>, you can use @click.self="handleParagraphClick" Commented Mar 11, 2020 at 22:39
  • @Phil, I've forgotten about 'self' event modifier. So, yes it should help me with my question. Thank you! Commented Mar 12, 2020 at 9:37

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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, GitHub
onPClick might need to be onPClick($event)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.