Home > Software engineering >  v-model with boolean and array type on same checkbox component
v-model with boolean and array type on same checkbox component

Time:09-01

I've got a BaseCheckbox component which has been used to bind and trigger single boolean values.

<template>
  <BaseCheckbox v-model="simpleBoolean" ... />
</template>
...
data() { 
  return { simpleBoolean: false }
}

Now, I want to bind multiple BaseCheckboxes via v-model to an array like its described in the docs.

<template>
  <BaseCheckbox v-model="fruits" value="apple" />
  <BaseCheckbox v-model="fruits" value="banana" />
</template>
...
data() { 
  return { fruits: [] }
}

However, I also want to keep the option to trigger simple boolean values within the same component. Here is an example project on stackblitz where you can reproduce my problem.

I want that fruits array is filled with the value of the checkbox like its done for nuts array. How to achieve this behaviour?

CodePudding user response:

This may not be the best way to do it but it works.

First of all, modelValue is an array, not a boolean. Add this to your BaseCheckbox as an array to make it fill the array:

handleInput(id) {
      if (!this.modelValue.includes(id)) {
        this.$emit('update:modelValue', [...this.modelValue, id]);
      } else {
        this.$emit(
          'update:modelValue',
          this.modelValue.filter((value) => value !== id)
        );
      }
    }

and then modify your input to remove checked:

<input :id="id" type="checkbox" v-bind="$attrs" @input="handleInput(id)" />

Also, modelValue should be an array, not a booleanright?

(Not sure whether this StackBlitz works.)

  • Related