4

Description

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!!

Code

<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>

Demo Links

Vue.js Ver.

I want this Vue version work as I expect. https://codesandbox.io/s/pjxzvj9jvm

Vanilla JavaScript Ver.

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

Animation GIFs

Vue.js Ver at codesandbox

enter image description here When I click the checkbox, what I want to see in the console is only "checkbox - change".

Vanilla JavaScript Ver at codepen

enter image description here

3
  • 3
    From your code, you just stop change event not click event. So this <input @click='$event.stopPropagation()' @change="checkboxChange" type="checkbox"> should works. Commented May 5, 2019 at 13:25
  • Thank you!! I tried it and it works as I expect!! Commented May 5, 2019 at 13:38
  • @click.stop="" should do it on the input element, if it has a v-model then you dont need a @change event. Commented Apr 27, 2022 at 5:21

1 Answer 1

7

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">
Sign up to request clarification or add additional context in comments.

2 Comments

What version of Vue is this solution for? When I try this in 2.6.14, my checkboxChange handler never gets called. I'm using a vuetify 1.5.24 checkbox, but from looking at the source code I don't think that should matter, since the @change and @click properties are among those passed into the subcomponent by a spread operation.
also @click.native.stop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.