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>

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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?

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.