Reputation: 3158
I have following structure in Vue3 template:
template:
/*html*/
`<div class='element1' @click='onClick'>
<img :src='image_url' />
<p>{{desc_text}}</p>
</div>`,
data() {
return {
image_url: "path/to/image",
desc_text: "Some text goes here"
}
},
methods: {
onClick(e) {
console.log(e);
}
}
Depending on where I click, console outputs e.target
to be either <img>
, <p>
or <div class='element1'>
, and it will have e.path
set to array of elements, from the element that was topmost under the pointer to the bottom-most, while currentTarget
is set to null
.
I am looking for a solution where event handler would be called with e.target
that points to the element that has @click listener added, in this case, <div class='element1'>
. Not to point to any of it's children.
I've been looking at Vue3 documentation on the event bubbles, but so far no modifiers fit my need.
For example @click.self
will only fire if e.target
is the element that has the event listener, however, if pointer was above any of it's children, it will not fire.
Right now, I use pointer-events: none;
styling on all children elements I don't want to have their own pointer event handling, which appears to have sufficient coverage. However, I'm surprised if Vue does not have any option on it's own to handle this case, maybe I am missing it?
I've read through Vue3 Event Modifiers document, but no option listed there does this.
In some cases, I have dozen of sub-elements in an element (eg. a card showing image, title, paragraph etc.), and I'd like entire element to be one big button to click on, with just one @click
event handler set.
Upvotes: 2
Views: 2406
Reputation: 1260
You can achieve same result (maybe better) without using event target but by passing arguments to the onClick handler.
What I usually do when rendering clickable list is that I pass the entire item
<div v-for="element in elements" :key="'element' + item.id" class="'element' + element.id" @click="onClick(element)">
<img :src='element.image_url' />
<p>{{element.desc_text}}</p>
</div>
It then become easy to handle the onclick as you already have the element you want at your disposal
onClick(element) {
console.log(element);
}
Upvotes: 1