Search code examples
javascriptvue.jsvuejs2vue-componentbootstrap-vue

Custom Bootstrap-Vue checkbox component


I’m trying to make components to create a dynamic form but I’m having trouble with checkboxes

<template v-if="type === 'switch'">
            <b-form-checkbox
                switch
                size="lg"
                :name="name"
                :id="name"
                :ref="name"
                :value="value"
                v-on:input.native="updateValue($event.target.value)"
                >{{ value }}</b-form-checkbox
            >
        </template>

Here's how I call the code

<FormRow
                type="switch"
                name="productor"
                rule="required"
                v-model="selectedCompany.productor"
            />

The problem is that the v-model content doesn't change but it does with input fields. What’s wrong? Can someone help me?

p.s. I’m working with bootstrap-vue Thank you!


Solution

  • You're missing v-model on the checkbox. Remove the value attribute and the input listener and use v-model with a computed setter to elegantly reuse the prop value from the parent as the model without mutating it:

    <b-form-checkbox
      switch
      size="lg"
      :name="name"
      :id="name"
      :ref="name"
      v-model="bvalue"
    >{{ value }}
    </b-form-checkbox>
    
    computed: {
      bvalue: {
        get() { return this.value },
        set(value) { this.$emit('input', value) }
      }
    }
    

    You can remove the updateValue method too.