Files
heroui-vue/apps/docs/components/switch.md
T
maoyingjie 145a208687 docs: close documentation facts, structure and related-component mapping
HD-04 scope, against heroui ce90ea3 cn sources:

- stale/fictional content: input.md no longer claims TextField is
  unmigrated; color-field.md no longer claims ColorPicker is private;
  header.md drops the fictional Header.Root subcomponent and the stale
  'menus not migrated' wording (MenuSection label registration is now
  documented from HeaderRoot source); radio-group.md drops three copied
  CheckboxGroup wordings (variant override is Radio's, scalar emits,
  native single-value submit); input-otp.md drops the fictional
  data-complete state and lists the real missing upstream props
- toggle-button disabled row now matches the real CSS hooks
  (:disabled / [aria-disabled], with data-disabled as a marker only)
- part API / CSS classes / interactive states restored per pinned
  sources: button (full class lists + real variable-based global CSS),
  accordion (per-part tables + variant/state lists), card (per-part
  tables + variant list), switch (SwitchGroup snippet + Switch/
  SwitchGroup class lists + states), color-field Group (class list +
  states), input-otp (variant notes, global CSS, class/state lists);
  input-group gains the two upstream usage chapters
- RelatedComponents restored from the pinned componentRelationships
  (first-3, filtered against componentsMap): 64 pages rewritten,
  list-box/slider sections added, 7 empty-mapping pages' fabricated
  entries removed; RelatedShowcases left unmigrated with its real data
  inventory recorded (2 cases, showcase-site cards)
- defaults unified on implementation evidence: granularity (inferred
  day/minute) and visibleYears (full min-max span, no "or 20" fallback);
  HD-03 hand-offs resolved (trigger focus-visible noted for HD-06,
  width guards kept)
- new demos: header-collection-grouping (MenuSection/ListBoxSection
  label wiring), empty-state-collection (collection empty slot);
  empty-state page deduplicated with a boundary compatibility note
- ComponentPreview minHeight/isBgSolid restored per the 30 upstream
  marks; tabs-overflow max-w-full kept after measuring internal scroll
- tests: +3 header registration/demo cases, +1 empty-state collection
  case; full suite 110 files / 1630 tests, typecheck and build:docs
  pass
2026-10-28 22:32:10 +08:00

257 lines
9.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: Switch 开关
description: 用于布尔状态的开关组件。
component: switch
group: 组件
---
## 用法
```vue
<script setup lang="ts">
import {
Switch,
SwitchContent,
SwitchControl,
SwitchThumb,
Description,
Label,
SwitchIcon,
SwitchGroup,
FieldError,
} from "@heroui-vue/components";
</script>
```
<ComponentPreview name="switch-basic" />
## 组件结构
```vue
<Switch>
<SwitchContent>
<SwitchControl>
<SwitchThumb>
<SwitchIcon /> <!-- 可选:滑块内图标 -->
</SwitchThumb>
</SwitchControl>
启用通知
</SwitchContent>
<Description>允许接收通知</Description>
</Switch>
```
请把 SwitchControl 与标签文本放入 SwitchContent;Description 作为其兄弟节点。Vue 底座使用原生 button 承载 role="switch",不是 React Aria 的 label 结构。
要对多个 Switch 进行分组,请使用 `SwitchGroup` 组件:
```vue
<SwitchGroup>
<Switch v-model:checked="option1">
<SwitchContent>
<SwitchControl><SwitchThumb /></SwitchControl>
选项一
</SwitchContent>
</Switch>
<Switch v-model:checked="option2">
<SwitchContent>
<SwitchControl><SwitchThumb /></SwitchControl>
选项二
</SwitchContent>
</Switch>
</SwitchGroup>
```
## 示例
### 尺寸
<ComponentPreview name="switch-sizes" />
### 带图标
<ComponentPreview name="switch-with-icons" />
### 禁用
<ComponentPreview name="switch-disabled" />
### 无标签
<ComponentPreview name="switch-without-label" />
### 带描述
<ComponentPreview name="switch-with-description" />
### 默认选中
<ComponentPreview name="switch-default-selected" />
### 受控组件
<ComponentPreview name="switch-controlled" />
### 标签位置
<ComponentPreview name="switch-label-position" />
### 分组
<ComponentPreview name="switch-group" />
### 横向分组
<ComponentPreview name="switch-group-horizontal" />
### 表单集成
<ComponentPreview name="switch-form" />
### 渲染属性
Vue 使用作用域插槽读取选择状态。
<ComponentPreview name="switch-render-props" />
### 渲染函数
Vue 使用 `asChild` 合并根容器属性,默认插槽必须只有一个自定义根元素;内部仍需放置 SwitchContent。
<ComponentPreview name="switch-render-function" />
## 自定义样式
### Tailwind CSS
<ComponentPreview name="switch-custom-styles" />
### 全局 CSS
若要自定义组件类,可使用 `@layer components` 指令;下面的类名与状态选择器都来自当前样式表:
```css
@layer components {
.hv-switch {
@apply inline-flex items-center gap-3;
}
.hv-switch__control {
@apply h-5 w-8 bg-gray-400 data-[selected=true]:bg-blue-500;
}
.hv-switch__thumb {
@apply bg-white shadow-sm;
}
.hv-switch__content {
@apply flex flex-col gap-1;
}
.hv-switch__icon {
@apply h-3 w-3 text-current;
}
}
```
## 样式参考
HeroUI 遵循 [BEM](https://getbem.com/) 方法论,确保组件变体与状态可复用且易于自定义。类名前缀为 `hv-`。
### CSS 类
#### Switch 类 [!toc]
Switch 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/switch.css)):
- `.hv-switch` - Switch 根容器(字段)
- `.hv-switch__content` - 包裹控件与标签文本的可点击 label
- `.hv-switch__control` - Switch 轨道
- `.hv-switch__thumb` - 可移动的滑块
- `.hv-switch__icon` - 滑块内可选图标
- `.hv-switch--sm` - 小尺寸变体
- `.hv-switch--md` - 中尺寸变体(默认)
- `.hv-switch--lg` - 大尺寸变体
#### SwitchGroup 类 [!toc]
SwitchGroup 组件使用以下 CSS 类([查看源码样式](https://github.com/heroui-inc/heroui/blob/v3/packages/styles/components/switch-group.css)):
- `.hv-switch-group` - Switch 组容器
- `.hv-switch-group__items` - Switch 项容器
- `.hv-switch-group--horizontal` - 横向布局
- `.hv-switch-group--vertical` - 纵向布局(默认)
### 交互状态
该 Switch 同时支持 CSS 伪类与 data 属性,以提供更灵活的状态控制:
- **已选中**:根上 `[data-selected="true"]` 或 `[aria-checked="true"]`(滑块位置与背景色变化)
- **悬停**:`:hover` 或 SwitchContent 上 `[data-hovered="true"]`(作用于 Control 轨道)
- **聚焦**:`:focus-visible` 或 SwitchContent 上 `[data-focus-visible="true"]`(在轨道上显示焦点环)
- **禁用**:根上 `[data-disabled="true"]`(降低透明度,包括帮助文本)
- **按压**:`:active` 或 SwitchContent 上 `[data-pressed="true"]`
只读与错误另有根上 `[data-readonly]`、`[data-invalid]` 标记。选中且禁用的组合配色由 `[data-selected="true"][data-disabled="true"]` 等复合规则提供。
## API 参考
### Switch
| Prop | 类型 | 默认值 | 描述 |
| -------------------- | --------------------------------------------------------------------- | ---------- | -------------------------------- |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | Switch 尺寸 |
| `checked` | `boolean` | — | Vue 受控值,使用 v-model:checked |
| `isSelected` | `boolean` | — | 上游同名受控属性,优先于 checked |
| `defaultSelected` | `boolean` | `false` | 非受控初始值 |
| `isDisabled` | `boolean` | `false` | 是否禁用 |
| `isReadOnly` | `boolean` | `false` | 是否只读 |
| `isInvalid` | `boolean` | `false` | ARIA 无效状态 |
| `isRequired` | `boolean` | `false` | 是否必须开启 |
| `name` | `string` | — | 表单字段名称 |
| `value` | `string` | — | 表单提交值 |
| `asChild` | `boolean` | `false` | 合并根属性到唯一自定义容器 |
| `validate` | `(value: boolean) => string \| string[] \| true \| null \| undefined` | — | 自定义校验 |
| `validationBehavior` | `'native' \| 'aria'` | `'native'` | 校验与错误展示方式 |
### SwitchContent / SwitchControl / SwitchThumb / SwitchIcon
分别对应上游 Content、Control、Thumb、Icon。Content 提供可点击的开关语义,其余为可组合样式部件。空默认插槽会自动渲染轨道与滑块;使用自定义插槽时由调用者组合部件。
### 事件与插槽
`update:checked`、`update:isSelected` 与 `change` 都传递 boolean。根作用域插槽提供 isSelected、isDisabled、isReadOnly、isInvalid、isRequired。根 attrs 的 class/style/data-* 应用到字段容器,ARIA 与 DOM 事件透传到 Content 按钮。
### 表单与校验
`validate(value)` 返回错误字符串、字符串数组,或 `true` / `null` / `undefined` 表示通过。`validationBehavior="native"`(默认)通过原生 checkbox 的约束阻止无效表单提交,校验失败后展示错误并将焦点交给开关;`"aria"` 立即设置 ARIA 错误状态,提交由调用者处理。
```vue
<Switch
name="consent"
is-required
:validate="(value) => (value ? true : '请先开启此选项。')"
>
<SwitchContent><SwitchControl><SwitchThumb /></SwitchControl>同意接收通知</SwitchContent>
<Description>可随时在设置中关闭。</Description>
<FieldError />
</Switch>
```
Description 与 FieldError 自动生成唯一 ID,并关联到 Content 的 aria-describedby。表单 reset 恢复非受控初值;受控值由父组件管理。
### SwitchGroup
| Prop | 类型 | 默认值 | 描述 |
| ------------- | ---------------------------- | ------------ | ---------- |
| `orientation` | `'horizontal' \| 'vertical'` | `'vertical'` | 组布局方向 |
SwitchGroup 是布局容器,每个 Switch 独立维护值;请提供 aria-label 或 aria-labelledby 标注分组。
### 当前差异
`disabled` / `required` / `defaultChecked` 作为兼容别名保留。`change` 事件传递 boolean;React Aria 的 PressEvent 仍不等价于 DOM click。根组件的 class/style/data-* 作用于字段容器,ARIA 与 DOM 事件作用于 Content 按钮;Content 上的显式属性可覆盖默认透传。`asChild` 替代 React render prop。Label / Description / FieldError 通过共享字段上下文接入 Switch;Form 的 `validationErrors` 按 name 映射、reset 与 `validationBehavior` 继承均已接入。
## 相关组件
[Label 标签](./label) · [Description 描述](./description) · [Button 按钮](./button)