[Vuejs]-@click bound to each item within v-for loop executed many times when clicking

0👍

The code you post seems fine. Although simplified here is the code you post running:

new Vue({
  el: 'ul',
  data: {
    options: [
      {
        value: 'option1',
      },
      {
        value: 'option2',
      }
    ]
  },
  methods: {
    handleClick(val) {
      console.log(val);
    },
  }
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<ul>
  <li :key="option.value" v-for="option in options">
    <div
      @click="handleClick(option.value)"
    >
      {{ option.value }}
    </div>
  </li>
</ul>

The problem must be elsewhere.

0👍

The culprit of the second click event triggered is the QuizCheckbox label element and its relations with its outmost div.

You actually have 2 click listeners. The one you assigned on the outmost div element and the second is on its input element assigned by JS. The latter is also triggered by click on label element.

You cannot click the outer div (what you expect to happen) separately of the inner label (if you click precisely on it). Your click on label produces the click event to bubble (see capturing and bubbling phases of JS events).

You could avoid the second trigger by using v-on:click.stop either on label or on input element.

Or you could manage the event within your handleClick($event, option.value) handler (see the $event passed as first argument) and decide how to respond based on e.g. event.target: this would be either label or the outer div element.

Leave a comment