# Checkbox

选择一个或多个选项，可以单独选，也可以成组选。

用复选框表示一个可以勾选或取消勾选的选项。几个选项属于同一个值时，用分组。

```vue title="basic.vue"
<script setup lang="ts">
import { CheckIcon } from "@lucide/vue"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/vue/checkbox"
</script>

<template>
  <label data-slot="label">
    <Checkbox>
      <CheckboxIndicator>
        <CheckIcon aria-hidden="true" />
      </CheckboxIndicator>
    </Checkbox>
    Accept terms and conditions
  </label>
</template>
```

点击复选框或它的标签，或聚焦它后按 Space，接受条款。

## 安装
```bash
npm install @ui-sdk/vue @ui-sdk/core
```

## 组合
用下面的组合构建一个 `Checkbox`：

```text
Checkbox
└── CheckboxIndicator
```

把复选框和它的文字包在一个 label 里。复选框已勾选或处于混合状态时，指示器会显示。

## 用法
导入部件并把它们组合起来：

```vue
<script setup lang="ts">
import { Checkbox, CheckboxIndicator } from "@ui-sdk/vue/checkbox"
</script>

<template>
  <label>
    <Checkbox>
      <CheckboxIndicator aria-hidden="true">✓</CheckboxIndicator>
    </Checkbox>
    Accept terms and conditions
  </label>
</template>
```

## 描述
选项需要更多说明时，用 `FieldLabel` 和 `FieldDescription`。字段会把标签和描述都连接到复选框。

```vue title="description.vue"
<script setup lang="ts">
import { CheckIcon } from "@lucide/vue"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/vue/checkbox"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/vue/field"
</script>

<template>
  <Field>
    <Checkbox>
      <CheckboxIndicator>
        <CheckIcon aria-hidden="true" />
      </CheckboxIndicator>
    </Checkbox>
    <div data-slot="stack">
      <FieldLabel>Accept terms and conditions</FieldLabel>
      <FieldDescription
        >By clicking this checkbox, you agree to the terms and
        conditions.</FieldDescription
      >
    </div>
  </Field>
</template>
```

点击 Accept terms and conditions。字段把标签和描述连接到复选框。

## 禁用
`disabled` 阻止聚焦和更改，并让复选框不参与表单提交。禁用的 `fieldset` 也一样。

```vue title="disabled.vue"
<script setup lang="ts">
import { CheckIcon } from "@lucide/vue"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/vue/checkbox"
</script>

<template>
  <div data-slot="stack">
    <label data-slot="label">
      <Checkbox default-checked>
        <CheckboxIndicator>
          <CheckIcon aria-hidden="true" />
        </CheckboxIndicator>
      </Checkbox>
      Product updates
    </label>
    <label data-slot="label">
      <Checkbox default-checked disabled>
        <CheckboxIndicator>
          <CheckIcon aria-hidden="true" />
        </CheckboxIndicator>
      </Checkbox>
      Security alerts
    </label>
  </div>
</template>
```

Security alerts 始终开启，所以那个复选框处于禁用状态。点击它的标签不会改变勾选状态。

## 只读
`read-only` 让复选框保持可聚焦并参与表单提交，同时阻止用户更改它。

```vue title="read-only.vue"
<script setup lang="ts">
import { CheckIcon } from "@lucide/vue"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/vue/checkbox"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/vue/field"
</script>

<template>
  <Field>
    <Checkbox name="two-factor" default-checked read-only>
      <CheckboxIndicator>
        <CheckIcon aria-hidden="true" />
      </CheckboxIndicator>
    </Checkbox>
    <div data-slot="stack">
      <FieldLabel>Require two-factor authentication</FieldLabel>
      <FieldDescription
        >Your organization requires this setting.</FieldDescription
      >
    </div>
  </Field>
</template>
```

按 Tab 到达已勾选的复选框。按 Space 或点击都不会改变这个设置。

## 不确定
不确定的复选框表示一个部分勾选的集合。它有 `aria-checked="mixed"` 和 `data-indeterminate`。按压会勾选它；只有你的代码能把它放回混合状态。

从 `default-checked="indeterminate"` 开始，或把 `"indeterminate"` 作为受控值传入。指示器的状态告诉它该显示哪个图标。[父复选框](https://ui-sdk.cn/docs/vue/components/checkbox#parent-checkbox)会替你从分组推导这个状态。

```vue
<Checkbox default-checked="indeterminate">
  <CheckboxIndicator v-slot="{ state }">
    <MinusIcon v-if="state.indeterminate" />
    <CheckIcon v-else />
  </CheckboxIndicator>
</Checkbox>
```

## 受控
用 `v-model:checked` 自己持有值。`createCheckboxController()` 创建的[控制器](https://ui-sdk.cn/docs/vue/components/checkbox#checkbox-controller)可以从任何地方更改它，比如下面的 Toggle 按钮。

```vue title="controlled.vue"
<script setup lang="ts">
import { CheckIcon } from "@lucide/vue"
import type { ChangeDetails } from "@ui-sdk/core"
import {
  createCheckboxController,
  type CheckedState,
} from "@ui-sdk/core/checkbox"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/vue/checkbox"
import { ref } from "vue"
import { useLog } from "./log"

const log = useLog()
const updates = createCheckboxController()
const checked = ref<CheckedState>(false)

function onCheckedChange(next: CheckedState, details: ChangeDetails) {
  log(
    `${next === "indeterminate" ? "Mixed" : next ? "Checked" : "Unchecked"} (${details.reason})`
  )
}
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <button type="button" @click="updates.toggle()">Toggle</button>
    </div>
    <label data-slot="label">
      <Checkbox
        v-model:checked="checked"
        :controller="updates"
        @checked-change="onCheckedChange"
      >
        <CheckboxIndicator>
          <CheckIcon aria-hidden="true" />
        </CheckboxIndicator>
      </Checkbox>
      Email me about product updates
    </label>
  </div>
</template>
```

更改复选框，或按 Toggle。控制台会记录每次变更及其原因。

## 表单
设置 `name` 和 `value`，让已勾选的复选框进入原生表单。未勾选和混合状态的复选框不提交任何内容。默认值是 `"on"`。独立的复选框可以共用一个 `name` 来提交多个值；应用还需要一份已勾选值的列表时，用[分组](https://ui-sdk.cn/docs/vue/components/checkbox#group)。

`required` 会阻止提交，直到复选框被勾选。Reset 会把它恢复到 `default-checked`。把 `form` 设为表单的 id，就能从页面其他地方加入该表单。

```vue title="form.vue"
<script setup lang="ts">
import { CheckIcon } from "@lucide/vue"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/vue/checkbox"
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/vue/field"
import { useLog } from "./log"

const log = useLog()

function onSubmit(event: Event) {
  const entries = [...new FormData(event.currentTarget as HTMLFormElement)].map(
    ([name, value]) => `${name}=${value}`
  )
  log(entries.length ? `Submitted ${entries.join("&")}` : "Submitted nothing")
}
</script>

<template>
  <form data-slot="stack" @submit.prevent="onSubmit">
    <Field>
      <Checkbox name="terms" value="yes" required>
        <CheckboxIndicator>
          <CheckIcon aria-hidden="true" />
        </CheckboxIndicator>
      </Checkbox>
      <div data-slot="stack">
        <FieldLabel>Accept terms and conditions</FieldLabel>
        <FieldDescription
          >You agree to our Terms of Service and Privacy
          Policy.</FieldDescription
        >
      </div>
    </Field>
    <Field>
      <Checkbox name="newsletter" value="weekly" default-checked>
        <CheckboxIndicator>
          <CheckIcon aria-hidden="true" />
        </CheckboxIndicator>
      </Checkbox>
      <div data-slot="stack">
        <FieldLabel>Send me the weekly newsletter</FieldLabel>
        <FieldDescription
          >Product news and tips, once a week. Unsubscribe
          anytime.</FieldDescription
        >
      </div>
    </Field>
    <div data-slot="row">
      <button type="submit">Create Account</button>
      <button type="reset">Reset</button>
    </div>
  </form>
</template>
```

在条款未勾选的情况下创建账户，查看原生校验，然后接受条款并重试。控制台会记录提交的内容，Reset 会恢复默认值。

## 分组
`CheckboxGroup` 维护一份已勾选值的列表。每个复选框提供它的 `value`；分组按复选框出现的顺序返回选中的值。用 `aria-label`、`aria-labelledby` 或 [Field](https://ui-sdk.cn/docs/vue/components/checkbox#group-in-a-form) 为分组命名。

```vue title="group.vue"
<script setup lang="ts">
import { CheckIcon } from "@lucide/vue"
import {
  Checkbox,
  CheckboxGroup,
  CheckboxIndicator,
} from "@ui-sdk/vue/checkbox"

const toppings = [
  { value: "cheese", label: "Cheese" },
  { value: "mushrooms", label: "Mushrooms" },
  { value: "olives", label: "Olives" },
  { value: "peppers", label: "Peppers" },
]
</script>

<template>
  <div data-slot="stack">
    <h3 id="basic-toppings">Toppings</h3>
    <CheckboxGroup aria-labelledby="basic-toppings" :default-value="['cheese']">
      <label data-slot="label" v-for="topping in toppings" :key="topping.value">
        <Checkbox :value="topping.value">
          <CheckboxIndicator>
            <CheckIcon aria-hidden="true" />
          </CheckboxIndicator>
        </Checkbox>
        {{ topping.label }}
      </label>
    </CheckboxGroup>
  </div>
</template>
```

选择多种配料。分组维护一份已勾选值的列表。

## 父复选框
添加一个带 `parent` 的复选框，用来勾选或取消勾选整个分组。所有值都选中时它处于勾选状态，一个都没有时处于未勾选状态，其余情况为混合状态。它用 `aria-controls` 指向子复选框，自身不提交任何内容。

把 `all-values` 传给分组，让父复选框在首次渲染时就有正确的状态，在服务器上也是如此。否则它要等复选框挂载后才能发现这些值。

```vue title="group-parent.vue"
<script setup lang="ts">
import { CheckIcon, MinusIcon } from "@lucide/vue"
import {
  Checkbox,
  CheckboxGroup,
  CheckboxIndicator,
} from "@ui-sdk/vue/checkbox"

const toppings = [
  { value: "cheese", label: "Cheese" },
  { value: "mushrooms", label: "Mushrooms" },
  { value: "olives", label: "Olives" },
  { value: "peppers", label: "Peppers" },
]
</script>

<template>
  <div data-slot="stack">
    <h3 id="parent-toppings">Toppings</h3>
    <CheckboxGroup
      aria-labelledby="parent-toppings"
      :default-value="['cheese', 'olives']"
      :all-values="toppings.map((topping) => topping.value)"
    >
      <label data-slot="label">
        <Checkbox parent>
          <CheckboxIndicator>
            <CheckIcon aria-hidden="true" />
            <MinusIcon aria-hidden="true" />
          </CheckboxIndicator>
        </Checkbox>
        Select all
      </label>
      <div data-slot="stack">
        <label
          data-slot="label"
          v-for="topping in toppings"
          :key="topping.value"
        >
          <Checkbox :value="topping.value">
            <CheckboxIndicator>
              <CheckIcon aria-hidden="true" />
            </CheckboxIndicator>
          </Checkbox>
          {{ topping.label }}
        </label>
      </div>
    </CheckboxGroup>
  </div>
</template>
```

Select all 会勾选每一种配料。取消勾选一种配料，Select all 就进入混合状态。

## 禁用的分组
禁用分组可以锁定每个复选框，或者禁用一个子项，只固定那个值。父复选框只会更改启用的子项。

```vue title="group-disabled.vue"
<script setup lang="ts">
import { CheckIcon, MinusIcon } from "@lucide/vue"
import {
  Checkbox,
  CheckboxGroup,
  CheckboxIndicator,
} from "@ui-sdk/vue/checkbox"

const backups = [
  { value: "photos", label: "Photos" },
  { value: "documents", label: "Documents" },
  { value: "messages", label: "Messages" },
]

const folders = [
  { value: "desktop", label: "Desktop", disabled: true },
  { value: "projects", label: "Projects", disabled: false },
  { value: "downloads", label: "Downloads", disabled: false },
]
</script>

<template>
  <div data-slot="stack">
    <div data-slot="stack">
      <h3 id="disabled-backups">Backups</h3>
      <p data-slot="hint">Managed by your organization.</p>
      <CheckboxGroup
        aria-labelledby="disabled-backups"
        :default-value="['photos', 'documents']"
        disabled
      >
        <label data-slot="label" v-for="item in backups" :key="item.value">
          <Checkbox :value="item.value">
            <CheckboxIndicator>
              <CheckIcon aria-hidden="true" />
            </CheckboxIndicator>
          </Checkbox>
          {{ item.label }}
        </label>
      </CheckboxGroup>
    </div>
    <div data-slot="stack">
      <h3 id="disabled-folders">Sync folders</h3>
      <CheckboxGroup
        aria-labelledby="disabled-folders"
        :default-value="['desktop']"
        :all-values="folders.map((item) => item.value)"
      >
        <label data-slot="label">
          <Checkbox parent>
            <CheckboxIndicator>
              <CheckIcon aria-hidden="true" />
              <MinusIcon aria-hidden="true" />
            </CheckboxIndicator>
          </Checkbox>
          Select all
        </label>
        <div data-slot="stack">
          <label data-slot="label" v-for="item in folders" :key="item.value">
            <Checkbox :value="item.value" :disabled="item.disabled">
              <CheckboxIndicator>
                <CheckIcon aria-hidden="true" />
              </CheckboxIndicator>
            </Checkbox>
            {{ item.label }}
          </label>
        </div>
      </CheckboxGroup>
    </div>
  </div>
</template>
```

Backups 分组已禁用。在 Sync folders 中，Select all 会更改启用的文件夹，而 Desktop 保持勾选。

## 受控的分组
用 `v-model:value` 自己持有选中的值。[控制器](https://ui-sdk.cn/docs/vue/components/checkbox#checkboxgroup-controller)可以替换这份列表，就像下面的 Select Weekdays 和 Clear 那样。

```vue title="group-controlled.vue"
<script setup lang="ts">
import { CheckIcon } from "@lucide/vue"
import type { ChangeDetails } from "@ui-sdk/core"
import { createCheckboxGroupController } from "@ui-sdk/core/checkbox"
import {
  Checkbox,
  CheckboxGroup,
  CheckboxIndicator,
} from "@ui-sdk/vue/checkbox"
import { ref } from "vue"
import { useLog } from "./log"

const days = [
  { value: "mon", label: "Monday" },
  { value: "tue", label: "Tuesday" },
  { value: "wed", label: "Wednesday" },
  { value: "thu", label: "Thursday" },
  { value: "fri", label: "Friday" },
  { value: "sat", label: "Saturday" },
  { value: "sun", label: "Sunday" },
]

const weekdays = ["mon", "tue", "wed", "thu", "fri"]

const log = useLog()
const schedule = createCheckboxGroupController()
const value = ref(["mon", "tue"])

function onValueChange(next: string[], details: ChangeDetails) {
  const names = days
    .filter((day) => next.includes(day.value))
    .map((day) => day.label)
  log(`${names.join(", ") || "No days"} (${details.reason})`)
}
</script>

<template>
  <div data-slot="stack">
    <div data-slot="controls">
      <button type="button" @click="schedule.setValue(weekdays)">
        Select Weekdays
      </button>
      <button type="button" @click="schedule.setValue([])">Clear</button>
    </div>
    <h3 id="controlled-days">Working days</h3>
    <CheckboxGroup
      v-model:value="value"
      aria-labelledby="controlled-days"
      :controller="schedule"
      @value-change="onValueChange"
    >
      <label data-slot="label" v-for="day in days" :key="day.value">
        <Checkbox :value="day.value">
          <CheckboxIndicator>
            <CheckIcon aria-hidden="true" />
          </CheckboxIndicator>
        </Checkbox>
        {{ day.label }}
      </label>
    </CheckboxGroup>
  </div>
</template>
```

选择工作日，或按 Select Weekdays 或 Clear。控制台会记录分组的值以及变更原因。

## 表单中的分组
在分组上设置 `name`，把每个已勾选的值都以该 name 提交。`required` 要求至少选择一项，Reset 会恢复 `default-value`。`disabled` 和 `form` 选项与单个复选框相同。

在字段中，字段提供分组的标签和描述，`FieldError` 会在选择让分组通过校验之前就地显示校验消息。[表单与校验](/docs/vue/forms)涵盖了共用的字段行为。

```vue title="group-field.vue"
<script setup lang="ts">
import { CheckIcon } from "@lucide/vue"
import {
  Checkbox,
  CheckboxGroup,
  CheckboxIndicator,
} from "@ui-sdk/vue/checkbox"
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/vue/field"
import { useLog } from "./log"

const channels = [
  { value: "email", label: "Email" },
  { value: "sms", label: "SMS" },
  { value: "push", label: "Push notifications" },
]

const log = useLog()

function onSubmit(event: Event) {
  const entries = [...new FormData(event.currentTarget as HTMLFormElement)].map(
    ([name, value]) => `${name}=${value}`
  )
  log(`Saved ${entries.join("&")}`)
}
</script>

<template>
  <form data-slot="stack" @submit.prevent="onSubmit">
    <Field>
      <FieldLabel>Notifications</FieldLabel>
      <FieldDescription
        >Choose how we tell you about your orders.</FieldDescription
      >
      <CheckboxGroup name="notifications" required>
        <label
          data-slot="label"
          v-for="channel in channels"
          :key="channel.value"
        >
          <Checkbox :value="channel.value">
            <CheckboxIndicator>
              <CheckIcon aria-hidden="true" />
            </CheckboxIndicator>
          </Checkbox>
          {{ channel.label }}
        </label>
      </CheckboxGroup>
      <div>
        <FieldError>Choose at least one way to be notified.</FieldError>
      </div>
    </Field>
    <button type="submit">Save</button>
  </form>
</template>
```

什么都不勾选就 Save，查看就地显示的错误。选择一种通知方式并保存；控制台会记录提交的值。

## 表格
同一个父复选框可以从表格表头中选择行。每一行提供它的值和无障碍名称。

```vue title="table.vue"
<script setup lang="ts">
import { CheckIcon, MinusIcon } from "@lucide/vue"
import {
  Checkbox,
  CheckboxGroup,
  CheckboxIndicator,
} from "@ui-sdk/vue/checkbox"
import { ref } from "vue"
import { useLog } from "./log"

const people = [
  {
    id: "hollis",
    name: "Hollis Grant",
    email: "hollis@example.com",
    role: "Owner",
  },
  {
    id: "ines",
    name: "Inès Moreau",
    email: "ines@example.com",
    role: "Editor",
  },
  {
    id: "kofi",
    name: "Kofi Mensah",
    email: "kofi@example.com",
    role: "Viewer",
  },
  {
    id: "wren",
    name: "Wren Takahashi",
    email: "wren@example.com",
    role: "Editor",
  },
]

const log = useLog()
const selected = ref(["hollis"])
</script>

<template>
  <CheckboxGroup
    v-model:value="selected"
    aria-label="Team members"
    :all-values="people.map((person) => person.id)"
    @value-change="
      (next: string[]) => log(`${next.length} of ${people.length} selected`)
    "
  >
    <table>
      <caption data-slot="visually-hidden">
        Team members
      </caption>
      <thead>
        <tr>
          <th>
            <Checkbox aria-label="Select all" parent>
              <CheckboxIndicator>
                <CheckIcon aria-hidden="true" />
                <MinusIcon aria-hidden="true" />
              </CheckboxIndicator>
            </Checkbox>
          </th>
          <th>Name</th>
          <th>Email</th>
          <th>Role</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="person in people" :key="person.id">
          <td>
            <Checkbox :value="person.id" :aria-label="`Select ${person.name}`">
              <CheckboxIndicator>
                <CheckIcon aria-hidden="true" />
              </CheckboxIndicator>
            </Checkbox>
          </td>
          <td>{{ person.name }}</td>
          <td>{{ person.email }}</td>
          <td>{{ person.role }}</td>
        </tr>
      </tbody>
    </table>
  </CheckboxGroup>
</template>
```

逐行选择，或使用表头里的 Select all。控制台会记录选中的行数。

## 动画
指示器出现时带有 `data-starting-style`，离开时带有 `data-ending-style`，并保持挂载直到退场结束。从这些状态过渡：

```css
[data-slot="checkbox-indicator"] {
  transition:
    opacity 0.15s,
    scale 0.15s;

  &:is([data-starting-style], [data-ending-style]) {
    opacity: 0;
    scale: 0.5;
  }
}
```

`keep-mounted` 让指示器在未勾选时也留在页面中，并带有 `data-unchecked`，用于同时展示两种状态的样式。

```vue title="indicator.vue"
<script setup lang="ts">
import { CheckIcon } from "@lucide/vue"
import { Checkbox, CheckboxIndicator } from "@ui-sdk/vue/checkbox"

const tasks = [
  { label: "Write the release notes", done: false },
  { label: "Update the changelog", done: true },
  { label: "Tag the release", done: false },
]
</script>

<template>
  <div data-slot="stack">
    <label data-slot="label" v-for="task in tasks" :key="task.label">
      <Checkbox :default-checked="task.done">
        <CheckboxIndicator>
          <CheckIcon aria-hidden="true" />
        </CheckboxIndicator>
      </Checkbox>
      {{ task.label }}
    </label>
  </div>
</template>
```

勾选再取消勾选一个任务。对勾会缩放并淡入，在卸载前淡出。

## 自定义渲染
复选框、指示器和分组都接受 `render` 插槽，它接收要绑定的 props 和部件的状态。把部件的 props 留在交互元素上，让它的角色、标签和键盘行为保持连接。

```vue title="render.vue"
<script setup lang="ts">
import { CheckIcon, PlusIcon } from "@lucide/vue"
import { Checkbox } from "@ui-sdk/vue/checkbox"

const topics = [
  { value: "design", label: "Design", checked: true },
  { value: "engineering", label: "Engineering", checked: false },
  { value: "marketing", label: "Marketing", checked: false },
  { value: "sales", label: "Sales", checked: false },
]
</script>

<template>
  <fieldset>
    <legend>Topics you follow</legend>
    <div data-slot="row">
      <Checkbox
        v-for="topic in topics"
        :key="topic.value"
        name="topics"
        :value="topic.value"
        :default-checked="topic.checked"
      >
        <template #render="{ props, state }">
          <button v-bind="props">
            <CheckIcon v-if="state.checked" />
            <PlusIcon v-else />
            {{ topic.label }}
          </button>
        </template>
      </Checkbox>
    </div>
  </fieldset>
</template>
```

选择主题。每个复选框渲染一个按钮，根据它的状态显示对勾或加号。

## 样式
用 `data-checked`、`data-unchecked` 和 `data-indeterminate` 表示勾选状态，用 `data-disabled`、`data-readonly` 和 `data-required` 表示其余状态。指示器会得到与它的复选框相同的状态属性。

每个部件都有一个 `data-slot`，比如 `checkbox`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/vue/components/checkbox#data-attributes)下。

## 数据属性
### Checkbox
`[data-slot="checkbox"]`

- `data-checked`: Present while checked.
- `data-disabled`: Present when disabled, by its own prop, a group or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-unchecked`: Present while unchecked.
- `data-indeterminate`: Present while indeterminate.

### CheckboxIndicator
`[data-slot="checkbox-indicator"]`

- `data-checked`: Present while checked.
- `data-disabled`: Present when disabled, by its own prop, a group or a `<fieldset>`.
- `data-readonly`: Present when read-only.
- `data-required`: Present when required.
- `data-unchecked`: Present while unchecked.
- `data-indeterminate`: Present while indeterminate.
- `data-starting-style`: Present for the indicator's first frame. Style the state you animate from.
- `data-ending-style`: Present while the indicator animates out. Style the state you animate to.

### CheckboxGroup
`[data-slot="checkbox-group"]`

- `data-disabled`: Present when the group is disabled, by its own prop or a `<fieldset>`.
- `data-required`: Present when at least one checkbox must be checked.

## API 参考
属性和下面相同。`onCheckedChange` 是 `v-model:checked`，需要原因时用 `@checked-change`，
`onValueChange` 是 `v-model:value`，需要原因时用 `@value-change`。

### Checkbox
- `checked?` (`CheckedState`): Whether it's checked. Pass it to control the checkbox.
- `defaultChecked?` (`CheckedState`): Whether it's checked at first, when uncontrolled. A form reset returns to it.
- `@checked-change` (`((checked: CheckedState, details: ChangeDetails<CheckboxCheckedChangeReason>) => void)`): Runs when a user or a form reset wants to change it. `details.reason` says why, and `details.cancel()` stops it.
- `disabled?` (`boolean`): Disables it like a native control: it can't be focused or changed, and isn't submitted.
- `readOnly?` (`boolean`): Keeps it focusable and submitted, but stops changes.
- `required?` (`boolean`): Blocks form submission until it's checked, with the browser's own message.
- `name?` (`string`): The name it submits under. Without one, it submits nothing.
- `value?` (`string`): What it submits while checked.
- `form?` (`string`): The id of a form to belong to, when it isn't inside that form.
- `controller?` (`{ toggle: (details?: Details) => boolean; getChecked: () => CheckedState; setChecked: (checked: CheckedState, details?: Details) => boolean; focus: () => void; }`): Toggles it from anywhere. Create one with `createCheckboxController()`.
- `parent?` (`boolean`): Makes it the parent of its group: it checks or unchecks every checkbox in the group, and shows checked, unchecked or indeterminate from them.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### CheckboxIndicator
- `keepMounted?` (`boolean`): Whether the indicator stays in the page while unchecked, so it can be styled or animated in both states.

### CheckboxGroup
- `value?` (`T[]`): The checked checkboxes' values. Pass it to control the group.
- `defaultValue?` (`T[]`): The values checked at first, when uncontrolled. A form reset returns to them.
- `@value-change` (`((value: T[], details: ChangeDetails<CheckboxGroupValueChangeReason>) => void)`): Runs when a user or a form reset wants to change the value. `details.reason` says why, and `details.cancel()` stops it.
- `allValues?` (`T[]`): Every value a parent checkbox checks. Without it, the parent checks the checkboxes in the group. Pass it to render the parent right on the server.
- `disabled?` (`boolean`): Disables every checkbox in the group, and leaves them out of the form.
- `readOnly?` (`boolean`): Makes every checkbox in the group read-only: focusable and submitted, but presses don't change it.
- `required?` (`boolean`): Blocks form submission until at least one checkbox is checked, with the browser's own message.
- `name?` (`string`): The name every checkbox in the group submits under.
- `form?` (`string`): The id of a form to belong to, when the group isn't inside that form.
- `controller?` (`{ getValue: () => T[]; setValue: (value: T[], details?: Details) => boolean; focus: () => void; }`): Checks values from anywhere. Create one with `createCheckboxGroupController()`.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### 状态
渲染函数、基于状态的类名和槽位收到什么。

- `checked` (`boolean`): Whether it's checked. False while indeterminate.
- `indeterminate` (`boolean`): Whether it's `"indeterminate"`, for a partly checked group. A press makes it checked.
- `disabled` (`boolean`): Whether it's disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether it's read-only: it stays focusable and submitted, but presses don't change it.
- `required` (`boolean`): Whether a form won't submit until it's checked. Indeterminate doesn't count.

指示器收到相同的状态。

- `checked` (`boolean`): Whether it's checked. False while indeterminate.
- `indeterminate` (`boolean`): Whether it's `"indeterminate"`, for a partly checked group. A press makes it checked.
- `disabled` (`boolean`): Whether it's disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether it's read-only: it stays focusable and submitted, but presses don't change it.
- `required` (`boolean`): Whether a form won't submit until it's checked. Indeterminate doesn't count.

分组：

- `value` (`string[]`): The checked values.
- `disabled` (`boolean`): Whether the group is disabled, by itself or by a `<fieldset>`.
- `readOnly` (`boolean`): Whether the group is read-only: its checkboxes stay focusable and submitted, but presses don't change them.
- `required` (`boolean`): Whether a form won't submit until at least one of its checkboxes is checked.

### 原因
`details.reason` 说明勾选状态为什么改变。

- `press` (`MouseEvent | KeyboardEvent`): A single-element control was pressed: a checkbox, a switch or a toggle.
- `reset` (`none`): A form reset.
- `restore` (`none`): The browser restored state, like after going back, or a saved value was read back from storage.
- `imperative` (`none`): A controller or `api` call.

对分组来说，它说明已勾选的值为什么改变。

- `item-press` (`MouseEvent | KeyboardEvent`): A member of a collection was chosen: a menu item, a tab, a radio or a checkbox item.
- `reset` (`none`): A form reset.
- `restore` (`none`): The browser restored state, like after going back, or a saved value was read back from storage.
- `imperative` (`none`): A controller or `api` call.

### Checkbox 控制器
用 `createCheckboxController()` 创建一个，并作为 `controller` 传入。

每个写入方法都接受可选的 `{ reason, event }`，像按压一样运行变更回调，并在变更被取消时返回 `false`。

- `toggle(details?)` (`(details?: CheckboxChangeOptions | undefined) => boolean`): Checks it, or unchecks it. An indeterminate checkbox becomes checked.
- `getChecked()` (`() => CheckedState`): Whether it's checked: `true`, `false` or `"indeterminate"`.
- `setChecked(checked, details?)` (`(checked: CheckedState, details?: CheckboxChangeOptions | undefined) => boolean`): Sets whether it's checked, as a user would.
- `focus()` (`() => void`): Moves focus to it.

### CheckboxGroup 控制器
用 `createCheckboxGroupController()` 创建一个，并作为 `controller` 传入。

它的写入方法与复选框控制器相同。

- `getValue()` (`() => T[]`): The checked values.
- `setValue(value, details?)` (`(value: T[], details?: CheckboxGroupChangeOptions | undefined) => boolean`): Sets the checked values, as a user would. A disabled group ignores it.
- `focus()` (`() => void`): Moves focus to the first enabled checkbox.

### 事件
事件先收到新状态或新值，再收到详情。只有变更事件未被取消时，`v-model` 才会更新。

| 绑定              | 所属部件        | 收到                                                                             |
| ----------------- | --------------- | -------------------------------------------------------------------------------- |
| `v-model:checked` | `Checkbox`      | 勾选状态                                                                         |
| `@checked-change` | `Checkbox`      | `(checked, details)`：`true`、`false` 或 `"indeterminate"`，以及[原因](https://ui-sdk.cn/docs/vue/components/checkbox#reasons) |
| `v-model:value`   | `CheckboxGroup` | 已勾选的值                                                                       |
| `@value-change`   | `CheckboxGroup` | `(value, details)`：已勾选的值，以及[原因](https://ui-sdk.cn/docs/vue/components/checkbox#reasons)                             |

## 无障碍
复选框遵循 [WAI-ARIA 复选框模式](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/)，分组的父复选框遵循它的[混合复选框示例](https://www.w3.org/WAI/ARIA/apg/patterns/checkbox/examples/checkbox-mixed/)。`Checkbox` 渲染一个带 `checkbox` 角色的按钮，以及一个参与表单的隐藏原生复选框。下面每一行都是一个自动化测试。

### 键盘
| Key   | 作用                                         |
| ----- | -------------------------------------------- |
| Tab   | 移动到下一个复选框                           |
| Space | 勾选或取消勾选它，或勾选一个混合状态的复选框 |
| Enter | 提交它的表单                                 |

### 经过测试的行为
**Checkbox**

- Clicking toggles it.
- Clicking its label toggles it.
- Clicking a label around it toggles it once.
- Space toggles it.
- Enter submits the form and never toggles it.
- Tab moves through checkboxes in order.
- The indicator shows only while checked.
- A change can be cancelled.
- A controlled checkbox follows its value.
- A read-only checkbox can be focused but not changed.
- Exit keyframes keyed on data-unchecked play before the indicator unmounts.
- An infinite exit animation still unmounts the indicator.

Runs in React、Vue 和 web components.

分组和父复选框：

- The group is named by its label.
- Starts on its default value.
- Checking a checkbox adds its value to the group.
- Every checked value submits under the group's name, in order.
- A reset returns to the default value.
- A required group blocks submission until one is checked.

**Parent checkbox**

- Is mixed while some checkboxes are checked.
- Checks every checkbox from mixed, then unchecks them all.
- Is checked once every checkbox is.
- Submits nothing itself.

Runs in React、Vue 和 web components.

在表单中：

- The form submits every checked control's name and value.
- Unchecked controls submit nothing.
- A checkbox outside the form joins it with the form attribute.
- Required controls block submission.
- A form reset returns every control to its default.
- A reset returns to the default value, not to nothing.
- A disabled fieldset disables the controls inside it.
- A read-only control still submits.
- A user's change fires native input and change events on the form.

Runs in React、Vue 和 web components.

在模式基线之外：

**Enhancements**

- The first invalid control takes focus in document order.
- A later required field without an error part doesn't take focus from the first.

**Form-associated custom elements**

- Take part in the form with no hidden input. Web components only.
- Report validity like native controls. Web components only.
- Have live checked and value properties. Web components only.
- Are named by their labels. Web components only.

Runs in React、Vue 和 web components.

在每个经过测试的框架里，屏幕阅读器听到的内容相同，由虚拟屏幕阅读器录制：

- Announcements while checking boxes with a keyboard.
- Announcements while choosing a radio with a keyboard.

Runs in React、Vue 和 web components.
