# CheckboxGroup

> 以数组管理一组独立复选项，复用 Checkbox 与既有表单合同。

网页来源：/components/checkbox-group

版本：@quirekit/ui 0.3.1；源码修订：d79a6b48d00e+worktree。此文档对应当前源码构建，接入方式以开始使用为准。

接入前置：[开始使用](/raw/components/getting-started.md)（Vue、样式、主题与图标 Provider）。

以字符串数组管理一组独立选项。每个选项提供唯一且非空的 `value` 和可读 `label`，可补充 `description`、`disabled`。

## 基础用法

`v-model` 管理选中值数组；`defaultValue` 设置非受控初始值。`label` 说明整组用途，默认纵向排列。

### 示例：checkbox-group/simple

文件：`simple.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import { QuireCheckboxGroup } from "@quirekit/ui/vue";

const values = ref(["email"]);
const items = [
  { value: "email", label: "工作邮件" },
  { value: "inbox", label: "站内通知" },
  { value: "digest", label: "每周摘要" },
];
</script>

<template>
  <div class="grid gap-4 p-qk-surface" data-checkbox-group-basic>
    <QuireCheckboxGroup v-model="values" :items="items" label="接收更新" />
    <output class="text-qk-helper text-qk-text-secondary"
      >已选择 {{ values.length }} 种通知方式</output
    >
  </div>
</template>
```

## 全选组合

通过 `before` 插槽组合全选按钮。上下文提供 `allChecked`、`allDisabled`、`readOnly`、`size` 和 `toggleAll`，可直接绑定到 Checkbox。

全选只改变可用选项。取消全选时，禁用项及当前未呈现的已有值仍保留在模型中。

### 示例：checkbox-group/basic

文件：`basic.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import type { QuireKitControlSize } from "@quirekit/ui";
import {
  QuireCheckboxGroup,
  QuireCheckbox,
  QuireSelect,
  QuireSwitch,
} from "@quirekit/ui/vue";
const values = ref(["archive"]);
const readOnly = ref(false);
const disabled = ref(false);
const size = ref<QuireKitControlSize>("sm");
const items = [
  {
    value: "email",
    label: "邮件通知",
    description: "重要更新发送到工作邮箱。",
  },
  { value: "message", label: "站内消息" },
  { value: "archive", label: "保留归档", disabled: true },
];
const sizes = ["xs", "sm", "md", "lg", "xl"].map((value) => ({
  value,
  label: value,
}));
</script>
<template>
  <div class="grid gap-qk-group p-qk-surface" data-checkbox-group-demo>
    <div class="flex flex-wrap items-center gap-4">
      <QuireSelect
        v-model="size"
        :items="sizes"
        label="复选组尺寸"
        class="w-24"
      /><QuireSwitch v-model:checked="readOnly" label="只读" /><QuireSwitch
        v-model:checked="disabled"
        label="禁用"
      />
    </div>
    <QuireCheckboxGroup
      v-model="values"
      :items="items"
      label="通知与留存"
      :size="size"
      :read-only="readOnly"
      :disabled="disabled"
    >
      <template #before="group"
        ><QuireCheckbox
          label="全选可用选项"
          :checked="group.allChecked"
          :disabled="group.allDisabled"
          :read-only="group.readOnly"
          :size="group.size"
          @update:checked="group.toggleAll()"
      /></template>
    </QuireCheckboxGroup>
    <p class="text-qk-text-secondary" data-choice-value>
      当前值：{{ values.join("、") || "无" }}
    </p>
  </div>
</template>
```

## 尺寸与方向

`size` 支持 `xs` 至 `xl`，默认 `sm`；`orientation="horizontal"` 横向排列，空间不足时换行。外层 Field 已有标签时可设置 `hideLabel`，同时保留组的可访问名称。

### 示例：checkbox-group/layout

文件：`layout.vue`

```vue
<script setup lang="ts">
import { QuireCheckboxGroup } from "@quirekit/ui/vue";

const sizes = ["xs", "sm", "md", "lg", "xl"] as const;
const items = [
  { value: "body", label: "正文" },
  { value: "comments", label: "批注" },
];
</script>

<template>
  <div class="grid gap-4 p-qk-surface">
    <QuireCheckboxGroup
      v-for="size in sizes"
      :key="size"
      :size="size"
      :label="`${size} 导出内容`"
      :items="items"
      :default-value="['body']"
      orientation="horizontal"
    />
  </div>
</template>
```

## 只读、禁用与错误

`readOnly` 禁止修改并保留焦点与值；`disabled` 禁止交互和原生提交。`invalid` 展示外部校验结果，单项 `disabled` 只锁定对应选项。

### 示例：checkbox-group/states

文件：`states.vue`

```vue
<script setup lang="ts">
import { QuireCheckboxGroup } from "@quirekit/ui/vue";
const items = [
  { value: "email", label: "邮件" },
  { value: "message", label: "站内信" },
  { value: "sms", label: "短信", disabled: true },
];
</script>
<template>
  <div class="grid gap-qk-group p-qk-surface" data-checkbox-group-states>
    <QuireCheckboxGroup label="空选择" :items="items" />
    <QuireCheckboxGroup
      label="只读通知"
      :items="items"
      :default-value="['email']"
      read-only
    />
    <QuireCheckboxGroup
      label="禁用通知"
      :items="items"
      :default-value="['message']"
      disabled
    />
    <QuireCheckboxGroup label="至少选择一种通知" :items="items" invalid />
  </div>
</template>
```

## 表单与必填

数组必填由 `QuireFormField` 校验；不要给每个 Checkbox 都加 `required`，否则会要求全部选中。将字段值收窄为字符串数组，再通过公开 `controlProps` 传递状态与事件。

### 示例：choice-groups/form

文件：`form.vue`

```vue
<script setup lang="ts">
import { ref } from 'vue';
import { QuireForm, QuireFormField, QuireCheckboxGroup, QuireToggleGroup, QuireButton, QuireSwitch } from '@quirekit/ui/vue';
const readOnly = ref(false);
const disabled = ref(false);
const result = ref('尚未提交');
const items = [{ value: 'email', label: '邮件' }, { value: 'message', label: '站内消息' }];
const modes = [{ value: 'compact', label: '紧凑' }, { value: 'comfortable', label: '舒适' }];
/**
 * Narrows the form's generic field value to this public array contract.
 * @param value - Form-owned unknown field value.
 * @returns Valid string array for the control binding.
 */
function stringValues(value: unknown): string[] { return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []; }
/**
 * Records the validated host submission without a network side effect.
 * @param values - Current values owned by QuireForm.
 */
function save(values: Record<string, unknown>): void { result.value = JSON.stringify(values); }
</script>
<template>
  <div class="grid gap-qk-group p-qk-surface" data-choice-form-demo>
    <div class="flex flex-wrap gap-qk-surface"><QuireSwitch v-model:checked="readOnly" label="表单只读" /><QuireSwitch v-model:checked="disabled" label="表单禁用" /></div>
    <QuireForm validate-on="submit" :initial-values="{ channels: ['email'], density: ['compact'] }" :read-only="readOnly" :disabled="disabled" :on-submit="save">
      <QuireFormField v-slot="{ controlProps, value }" name="channels" label="接收通知" required required-message="至少选择一种通知方式">
        <QuireCheckboxGroup v-bind="controlProps" :model-value="stringValues(value)" :invalid="Boolean(controlProps.invalid)" :items="items" label="接收通知" hide-label orientation="horizontal" />
      </QuireFormField>
      <QuireFormField v-slot="{ controlProps, value }" name="density" label="显示密度" required>
        <QuireToggleGroup v-bind="controlProps" :model-value="stringValues(value)" :invalid="Boolean(controlProps.invalid)" :items="modes" label="显示密度" :deselectable="false" />
      </QuireFormField>
      <template #actions><QuireButton type="submit" variant="solid" color="primary" :disabled="disabled">保存偏好</QuireButton><QuireButton type="reset" variant="outline">重置</QuireButton></template>
    </QuireForm>
    <output class="text-qk-text-secondary" data-form-result>{{ result }}</output>
  </div>
</template>
```

直接使用原生表单时，选中且启用的条目以相同 `name` 重复提交，读取时使用 `FormData.getAll(name)`。模型中的未知值没有对应字段，不参与原生提交；受控模型的重置由宿主或 Form 管理。

## 键盘操作

| 按键 | 行为 |
| --- | --- |
| `Tab` | 依次聚焦可用复选项，包括全选。 |
| `Space` | 切换当前项；只读时保留原值。 |

## API

### QuireCheckboxGroup

#### Props

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| items | 是 | — | Ordered choices with stable unique values. |
| label | 是 | — | Accessible name for the entire group. |
| modelValue | 否 | — | Controlled values, owned by the host. |
| defaultValue | 否 | — | Initial non-controlled selection. |
| size | 否 | "sm" | Shared action/choice density. |
| orientation | 否 | "vertical" | Visual and keyboard arrangement. |
| disabled | 否 | false | Disable all options and native submission. |
| readOnly | 否 | false | Preserve focus and values while rejecting interactive changes. |
| name | 否 | — | Repeated native form field name. |
| form | 否 | — | External native form association. |
| invalid | 否 | false | Expose validation failure supplied by the owning field. |
| hideLabel | 否 | false | Keep the legend accessible without a second visible label. |

**items**

```ts
readonly QuireKitCheckboxGroupItem[]
```

```ts
readonly ({
  /** Stable unique value submitted with the group name. */
  value: string;
  /** Readable option name. */
  label: string;
  /** Optional supporting text. */
  description?: undefined | string;
  /** Preserve the stored value but disallow changes and submission. */
  disabled?: boolean | undefined;
})[]
```

**label**

```ts
string
```

**modelValue**

```ts
readonly string[] | undefined
```

```ts
undefined | readonly (string)[]
```

**defaultValue**

```ts
readonly string[] | undefined
```

```ts
undefined | readonly (string)[]
```

**size**

```ts
QuireKitControlSize | undefined
```

```ts
undefined | "xs" | "sm" | "md" | "lg" | "xl"
```

**orientation**

```ts
"vertical" | "horizontal" | undefined
```

```ts
undefined | "vertical" | "horizontal"
```

**disabled**

```ts
boolean | undefined
```

**readOnly**

```ts
boolean | undefined
```

**name**

```ts
string | undefined
```

```ts
undefined | string
```

**form**

```ts
string | undefined
```

```ts
undefined | string
```

**invalid**

```ts
boolean | undefined
```

**hideLabel**

```ts
boolean | undefined
```

#### Events

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| update\:modelValue | 否 | — |  |

**update:modelValue**

```ts
[value: string[]]
```

#### Slots

| 名称 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- |
| before | 否 | — | Compose a select-all checkbox or explanatory content before the options. |
| after | 否 | — | Content after all options. |
| item | 否 | — | Replace an item's label, retaining its native checkbox control. |

**before**

```ts
QuireKitCheckboxGroupContext
```

```ts
{
  /** Current host or local selection. */
  value: readonly (string)[];
  /** State derived from enabled items only. */
  allChecked: false | true | "indeterminate";
  /** Whether there are no enabled items or the whole group is disabled. */
  allDisabled: boolean;
  /** Read-only state for controls composed by the host. */
  readOnly: boolean;
  /** Shared size for composed controls. */
  size: "xs" | "sm" | "md" | "lg" | "xl";
  /** Toggle all enabled options while preserving other stored values. */
  toggleAll: { (): void; };
}
```

**after**

```ts
QuireKitCheckboxGroupContext
```

```ts
{
  /** Current host or local selection. */
  value: readonly (string)[];
  /** State derived from enabled items only. */
  allChecked: false | true | "indeterminate";
  /** Whether there are no enabled items or the whole group is disabled. */
  allDisabled: boolean;
  /** Read-only state for controls composed by the host. */
  readOnly: boolean;
  /** Shared size for composed controls. */
  size: "xs" | "sm" | "md" | "lg" | "xl";
  /** Toggle all enabled options while preserving other stored values. */
  toggleAll: { (): void; };
}
```

**item**

```ts
{ item: QuireKitCheckboxGroupItem; checked: boolean; }
```

```ts
{
  item: {
    /** Stable unique value submitted with the group name. */
    value: string;
    /** Readable option name. */
    label: string;
    /** Optional supporting text. */
    description?: undefined | string;
    /** Preserve the stored value but disallow changes and submission. */
    disabled?: boolean | undefined;
  };
  checked: boolean;
}
```

#### 公开实例成员

无。

#### 相关类型

```ts
type QuireKitCheckboxGroupItem = {
  /** Stable unique value submitted with the group name. */
  value: string;
  /** Readable option name. */
  label: string;
  /** Optional supporting text. */
  description?: undefined | string;
  /** Preserve the stored value but disallow changes and submission. */
  disabled?: boolean | undefined;
};
```

```ts
type QuireKitCheckboxGroupContext = {
  /** Current host or local selection. */
  value: readonly (string)[];
  /** State derived from enabled items only. */
  allChecked: false | true | "indeterminate";
  /** Whether there are no enabled items or the whole group is disabled. */
  allDisabled: boolean;
  /** Read-only state for controls composed by the host. */
  readOnly: boolean;
  /** Shared size for composed controls. */
  size: "xs" | "sm" | "md" | "lg" | "xl";
  /** Toggle all enabled options while preserving other stored values. */
  toggleAll: { (): void; };
};
```

```ts
type QuireKitControlSize = "xs" | "sm" | "md" | "lg" | "xl";
```
