Search code examples
javascriptvue.jsv-for

How to make a CheckBox list using <slot v-for> on VueJS?


I must make a checkbox list based on a array in data(). But I'm having two problems.

1. I just can select the first checkbox, when I tap on the other checkboxes the only value changed is of first checkbox's list.

2. I can't get @change function, that not is triggered when I change checkbox's value.

<template>
...
<slot
  v-for="(termo, index) in termos"
  v-bind="termo"
  >
  <generic-check-box
    class="terms"
    input-id="termos[index].id"
    v-model="termos[index].term"
    :value="termos[index].term"
    @change="checkBoxChanged(index)"
    >
    <generic-text
      color="gray"
      class="condition"
    >{{ termos[index].message }}
    </generic-text>
  </generic-check-box>
</slot>
</template>

<script>
export default {
  components: {
    'close-button': CloseButton,
    'generic-button': GenericButton,
    'generic-check-box': GenericCheckBox,
    'generic-combo-box': GenericComboBox,
    'generic-title': GenericTitle,
    'generic-text': GenericText,
    'off-canvas-buttons': OffCanvasButtons
  },
  data () {
    return {
      termos: [
        { id: 0, term: true, message: 'Message 1' },
        { id: 1, term: false, message: 'Message 2' },
        { id: 2, term: false, message: 'Message 3' },
        { id: 3, term: false, message: 'Message 4' }
      ]
    }
  },
  methods: {
    checkBoxChanged (index) {
      console.log('checkBoxChangled: ' + index + ' ' + this.termos[index].term)
    }
  }
}
</script>

enter image description here

EDIT

enter image description here


Solution

  • The main problem is this line:

    input-id="termos[index].id"
    

    It needs a : at the front:

    :input-id="termos[index].id"
    

    Otherwise input-id gets set to the string 'termos[index].id' for all of your checkboxes. That string then gets used as the id for the inputs and the for of the labels. When clicking on any of the labels it will only trigger the first input with that id.

    I would also note that your generic-check-box component doesn't appear to have a value prop defined. The other component is trying to use both value and v-model but these won't be passing in a value without a value prop.