自定义Bootstrap-Vue复选框组件

Custom Bootstrap-Vue checkbox component

我正在尝试制作组件来创建动态表单,但我在使用复选框时遇到了问题

<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>

下面是我调用代码的方式

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

问题是 v-model 内容没有改变,但输入字段改变了。怎么了?有人可以帮助我吗?

p.s。我正在使用 bootstrap-vue 谢谢!

您缺少 v-model 复选框。删除 value 属性和 input 侦听器并使用 v-modelcomputed setter 以优雅地重用父级的 prop 值作为模型而不改变它:

<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) }
  }
}

您也可以删除 updateValue 方法。

也许这些信息可以帮助: 我从设置 selectedCompany 状态的商店获取数据:{}, 然后从父组件(模态)我以这种方式绘制字段

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

在父级中,我执行以下操作:

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

methods: {
    updateValue: function(value) {
        this.$emit("input", value);
    }
},

在迁移文件中,我将字段生产器设置为默认值 (0) 的布尔值,在模型中,我以这种方式改变字段

 public function getProductorAttribute($value){
    return $value ? true : false;
}

现在一切都应该更清楚了