Lzh on GitHub

Switch

允许用户在选中和未选中之间切换的控件。
<script setup lang="ts">
import { SwitchRoot, SwitchThumb } from 'reka-ui'
import { ref } from 'vue'

const switchState = ref(false)
</script>

<template>
  <div class="flex gap-2 items-center">
    <label
      class="text-stone-700 dark:text-white text-sm leading-none pr-2 select-none"
      for="airplane-mode"
    >
      Airplane mode
    </label>

    <SwitchRoot
      id="airplane-mode"
      v-model="switchState"
      class="w-[32px] h-[20px] shadow-sm flex data-[state=unchecked]:bg-stone-300 data-[state=checked]:bg-stone-800 dark:data-[state=unchecked]:bg-stone-800 dark:data-[state=checked]:bg-stone-700 border border-stone-300 data-[state=checked]:border-stone-700  dark:border-stone-700 rounded-full relative transition-[background] focus-within:outline-none focus-within:shadow-[0_0_0_1px] focus-within:border-stone-800 focus-within:shadow-stone-800"
    >
      <SwitchThumb
        class="w-3.5 h-3.5 my-auto bg-white text-xs flex items-center justify-center shadow-xl rounded-full transition-transform translate-x-0.5 will-change-transform data-[state=checked]:translate-x-full"
      />
    </SwitchRoot>
  </div>
</template>

特性 (Features)

  • 完整的键盘导航。
  • 可控或非控。

安装 (Installation)

从命令行安装组件。

$ npm add reka-ui

结构 (Anatomy)

导入所有部件并组装它们。

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

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

API 参考 (API Reference)

根 (Root)

包含开关的所有部分。在 form 中使用时,也会渲染一个 input 以确保事件正确传播。

属性默认值类型描述
as'button'AsTag | Component此组件应渲染为的元素或组件。可通过 asChild 覆盖。
asChildboolean将默认渲染的元素替换为作为子元素传递的元素,合并它们的 props 和行为。阅读我们的组合指南了解更多详情。
defaultValueboolean开关初始渲染时的状态。当您不需要控制其状态时使用。
disabledbooleantrue 时,阻止用户与开关交互。
idstring
modelValueboolean | null开关的受控状态。可以通过 v-model 绑定。
namestring字段的名称。作为名称/值对的一部分随其所属的表单一起提交。
requiredbooleantrue 时,表示用户必须在提交所属表单之前设置值。
value'on'string作为数据提交时随 name 提交的值。

发送事件

事件名称Payload描述
update:modelValue[payload: boolean]开关值更改时调用的事件处理程序。

默认插槽

插槽参数插槽参数类型描述
modelValueboolean当前值

数据属性 (Data Attributes)

数据属性
[data-state]"checked" | "unchecked"
[data-disabled]禁用时存在

滑块 (Thumb)

用于视觉指示开关是开还是关的滑块。

属性默认值类型描述
as'span'AsTag | Component此组件应渲染为的元素或组件。可通过 asChild 覆盖。
asChildboolean将默认渲染的元素替换为作为子元素传递的元素,合并它们的 props 和行为。阅读我们的组合指南了解更多详情。

数据属性 (Data Attributes)

数据属性
[data-state]"checked" | "unchecked"
[data-disabled]禁用时存在

可访问性 (Accessibility)

遵循开关 (switch) 角色要求

键盘交互 (Keyboard Interactions)

按键描述
Space切换组件的状态。
Enter切换组件的状态。