Reputation: 244
I want to implement a table component with checkboxes. The problem I'm having is that when I click a checkbox, table row and table cell catch click event which I want to avoid. When I click a checkbox, I want only that checkbox react to the change event.
I tried event.stopPropagation
method but it does not work. Somehow, before the checkbox catches the change event, table row and cell containing that checkbox react to the click event when I click the checkbox.
How can I achieve what I want? Please help me!!
<template>
<table>
<tr @click="trClick">
<td @click="tdClick">
<input @change="checkboxChange" type="checkbox">
</td>
</tr>
</table>
</template>
<script>
export default {
name: "HelloWorld",
methods: {
trClick() {
console.log("tr - click");
},
tdClick() {
console.log("td - click");
},
checkboxChange(e) {
e.stopPropagation();
console.log("checkbox - change");
}
}
};
</script>
<style>
table {
background: #cccccc;
width: 100%;
cursor: pointer;
}
input {
cursor: pointer;
}
</style>
I want this Vue version work as I expect. https://codesandbox.io/s/pjxzvj9jvm
I just tried the same thing in vanilla JavaScript just in order to investigate how event propagation in JavaScript works. https://codepen.io/anon/pen/xNxgeM?editors=1111
When I click the checkbox, what I want to see in the console is only "checkbox - change".
Upvotes: 4
Views: 4990
Reputation: 7150
There is a built in solution in Vue to stop event propagation. Just use the @targetEvent.stop
notation:
<input @click.stop @change="checkboxChange" type="checkbox">
Upvotes: 7