首页 > 解决方案 > @click 绑定到 v-for 循环中的每个项目,单击时执行多次

问题描述

我有一个循环@click中的单个项目的绑定。v-for在生成的渲染中,我应该@click为每个项目设置一个,因此单击一个项目应该触发绑定到该项目的函数一次。

然而,它触发它的次数与物品的数量一样多。为什么?

<ul>
  <li :key="option.value" v-for="option in options">
    <QuizCheckbox
      @click.native="handleClick(option.value)"
    >
      {{ option.value }}
    </QuizCheckbox>
  </li>
</ul>

...

methods: {
  handleClick(val) {
    console.log(val);
  },

编辑:如果我用一个简单的元素替换 ...,那么单击它不会触发问题。因此,<QuizCheckbox>罪魁祸首是组件。但是,其中似乎没有任何内容表明可能导致问题的原因。以下是 的内容QuizCheckbox.vue

<template>
  <div :class="['quiz-checkbox', {'quiz-checkbox--checked': shouldBeChecked}]">
    <div :class="['form-checkbox']">
      <label class="form-checkbox__label">
        <slot/>
        <input
          :checked="shouldBeChecked"
          :value="value"
          @change="updateInput"
          class="form-checkbox__input"
          type="checkbox"
        />
        <span class="form-checkbox__checkmark"></span>
      </label>
    </div>
  </div>
</template>

<script>
export default {
  model: {
    prop: 'modelValue',
    event: 'change'
  },
  props: {
    value: {
      type: String,
    },
    modelValue: {
      type: [Boolean, Array],
      default: false
    }
  },
  computed: {
    shouldBeChecked() {
      if (this.modelValue instanceof Array) {
        return this.modelValue.includes(this.value);
      }
      return this.modelValue;
    }
  },
  created() {
    if (!this.$slots.default) {
      console.error('QuizCheckbox: requires label to be provided in the slot');
    }
  },
  methods: {
    updateInput(event) {
      const isChecked = event.target.checked;

      if (this.modelValue instanceof Array) {
        const newValue = [...this.modelValue];

        if (isChecked) {
          newValue.push(this.value);
        } else {
          newValue.splice(newValue.indexOf(this.value), 1);
        }

        this.$emit('change', newValue);
      } else {
        this.$emit('change', isChecked);
      }
    }
  }
};
</script>

标签: vue.jsv-for

解决方案


您发布的代码似乎很好。尽管此处简化了您发布的运行代码:

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>

问题一定出在其他地方。


推荐阅读