backdrop
组件

Switch 开关

允许用户在选中与未选中状态之间切换的控件。

功能特性

  • 支持完整的键盘导航。
  • 可受控或非受控使用。

安装

通过命令行安装该组件。

sh
$ npm add reka-ui

结构

导入所有部件并组装在一起。

vue
<script setup>
import { SwitchRoot, SwitchThumb } from 'reka-ui'
</script>

<template>
  <SwitchRoot>
    <SwitchThumb />
  </SwitchRoot>
</template>

API 参考

Root 根组件

包含开关的所有组成部分。在 form 表单内使用时,还会渲染一个 input 元素以确保事件正确传播。

PropDefaultType
as
'button'
AsTag | Component

The element or component this component should render as. Can be overwritten by asChild.

asChild
boolean

Change the default rendered element for the one passed as a child, merging their props and behavior.

Read our Composition guide for more details.

defaultValue
boolean

The state of the switch when it is initially rendered. Use when you do not need to control its state.

disabled
boolean

When true, prevents the user from interacting with the switch.

id
string
modelValue
boolean | null

The controlled state of the switch. Can be bind as v-model.

name
string

The name of the field. Submitted with its owning form as part of a name/value pair.

required
boolean

When true, indicates that the user must set the value before the owning form can be submitted.

value
'on'
string

The value given as data when submitted with a name.

EmitPayload
update:modelValue
[payload: boolean]

Event handler called when the value of the switch changes.

Slots (default)Payload
modelValue
boolean

Current value

Data AttributeValue
[data-state]"checked(已选中)" | "unchecked(未选中)"
[data-disabled]禁用时出现

Thumb 开关滑块

用于视觉指示开关开启或关闭状态的滑块。

PropDefaultType
as
'span'
AsTag | Component

The element or component this component should render as. Can be overwritten by asChild.

asChild
boolean

Change the default rendered element for the one passed as a child, merging their props and behavior.

Read our Composition guide for more details.

Data AttributeValue
[data-state]"checked(已选中)" | "unchecked(未选中)"
[data-disabled]禁用时出现

无障碍访问

遵循 switch 角色要求

键盘交互

KeyDescription
空格键
切换组件的状态。
回车键
切换组件的状态。