You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Bootstrap复选框组默认值设置为选中状态?

Bootstrap Vue复选框组默认全选解决方案

问题

我有一个包含21个复选框的Bootstrap复选框组,该组绑定到一个数组。目前所有复选框默认未选中,我希望它们默认全部选中。查阅文档发现,checked="true"仅对单个复选框生效。尝试手动向visibleFieldKeys数组添加多个true值,但无效果且代码不美观,请问如何实现复选框组默认全选?

代码示例

<b-row>
  <b-col lg="2" class="mb-3">
    <b-form-checkbox-group stacked v-if="selectedPropertyId && tableLayout" v-model="visibleFieldKeys" :options="fields.slice(0,7)" text-field="label" value-field="key" inline/>
  </b-col>
  <b-col lg="2" class="mb-3">
    <b-form-checkbox-group stacked v-if="selectedPropertyId && tableLayout" v-model="visibleFieldKeys" :options="fields.slice(7,14)" text-field="label" value-field="key" inline/>
  </b-col>
  <b-col lg="2" class="mb-3">
    <b-form-checkbox-group stacked v-if="selectedPropertyId && tableLayout" v-model="visibleFieldKeys" :options="fields.slice(14,21)" text-field="label" value-field="key" inline/>
  </b-col>
</b-row>

尝试过的无效代码

visibleFieldKeys: [true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,]

解决方案

你之前的问题出在没搞懂b-form-checkbox-group的v-model绑定规则——它绑定的不是布尔值数组,而是选中项的value-field对应的值组成的数组。所以手动塞一堆true肯定没用,正确的做法是把所有选项的key值放进visibleFieldKeys里。

具体操作分两种情况:

  • 静态字段数据:如果fields是组件预先定义的静态数据,在组件初始化时提取所有key:

    data() {
      return {
        fields: [/* 你的21个字段,每个包含label和key属性 */],
        visibleFieldKeys: []
      }
    },
    created() {
      // 提取所有字段的key,赋值给绑定数组实现全选
      this.visibleFieldKeys = this.fields.map(item => item.key);
    }
    
  • 异步字段数据:如果fields是从接口获取的,要等数据加载完成后再赋值:

    data() {
      return {
        fields: [],
        visibleFieldKeys: []
      }
    },
    async mounted() {
      // 模拟接口请求获取字段数据
      const response = await fetch('/your-api-endpoint');
      this.fields = await response.json();
      // 数据加载完成后设置全选
      this.visibleFieldKeys = this.fields.map(item => item.key);
    }
    

这样处理后,三个复选框组的所有选项会自动默认选中,代码简洁易维护,不用手动写21个重复值。

内容的提问来源于stack exchange,提问作者Scandidi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 05:16:27