1

I get how to bind multiple checkboxes to an array in Vue. But when I try to put the checkboxes into their own component and bind to an array using v-model it doesn't seem to work. Does anyone have any idea why?

CheckboxSelection.vue

<template>
  <div  v-for="(check,index) in checks" :key="index">
    <input  v-model="model"
            :value="check.value"
            :id="check.id"
            type="checkbox" />
  </div>
</template>

<script>
export default {
  props: {
    value: Array
  },
  data(){
    return {
      model: this.value,
      checks: [
        {
          id: 1,
          label: 'Check 1',
          value: 'check1'
        },
        {
          id: 2,
          label: 'Check 2',
          value: 'check2'
        }
      ]
    }
  },
  watch: {
    model: function(val) {
      this.$emit("input", val)
    }
  },
}
</script>

Usage:

<CheckboxSelection v-model="selection"></CheckboxSelection>
Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
user2424495
  • 573
  • 1
  • 6
  • 19

1 Answers1

2

In vue 3 value prop has been changed to modelValue and the emitted event input to update:modelValue :

export default {
  props: {
    modelValue: Array
  },
emits:["update:modelValue"],
  data(){
  ....
  },
  watch: {
    model: function(val) {
      this.$emit("update:modelValue", val)
    }
  },
}

for the script setup syntax please check my answer here

Boussadjra Brahim
  • 82,684
  • 19
  • 144
  • 164
  • I've just realised that clearing the bound value (in my example called 'selection') does not clear the checkboxes states (though the modelValue seems to be empty) - do you know a solution to that? – user2424495 Jul 10 '21 at 14:36