Skip to content

Switch 开关

表示两种相互对立的状态间的切换,多用于触发「开/关」。

基础用法

绑定 v-model 到一个 Boolean 类型的变量。

基础用法

尺寸

通过 size 属性可以设置 Switch 的大小。

尺寸

文字描述

使用 active-text 属性与 inactive-text 属性来设置开关的文字描述。使用 inline-prompt 属性来控制文本是否显示在点内。

Y
文字描述

显示自定义图标

使用 active-iconinactive-icon 属性来添加图标。使用 inline-prompt 属性来控制图标显示在点内。

显示自定义图标

扩展的 value 类型

你可以设置 active-valueinactive-value 属性,它们接受 BooleanStringNumber 类型的值。

Value: 100
扩展的 value 类型

禁用状态

设置 disabled 属性,接受一个 Boolean,设置 true 即可禁用。

禁用状态

加载状态

设置 loading 属性,接受一个 Boolean,设置 true 即显示加载状态。

加载状态

阻止切换

设置 before-change 属性,若返回 false 或者返回 Promise 且被 reject,则停止切换。

阻止切换

自定义动作图标

使用 active-action-iconinactive-action-icon 属性来自定义滑块内的图标。

自定义动作图标

在 Nuxt 中使用

Switch 组件完全支持 Nuxt 3/4 的 SSR 渲染。在 Nuxt 项目中使用时,组件会自动导入。

关闭
开启
Nuxt 中使用

SSR 注意事项

  • ✅ 基础开关状态、尺寸样式完全支持
  • ✅ 文字描述及图标在 SSR 中渲染一致
  • ✅ 扩展 Value 类型(active-value)支持
  • ⚠️ 初始状态在 SSR 完成后与客户端激活一致

SSR 安全性

Switch 组件针对 SSR 进行了深度适配,确保滑块位置和颜色在服务端渲染时就被正确计算,提供流畅的视觉体验。

API

Props

属性名说明类型默认值
model-value / v-model绑定值,必须等于 active-valueinactive-value,默认为 Boolean 类型boolean | string | numberfalse
disabled是否禁用booleanfalse
loading是否显示加载中booleanfalse
sizeswitch 的大小'large' | 'default' | 'small''default'
widthswitch 的宽度number | string
inline-prompt图标或文本是否显示在点内,开启时文本最多呈现 3 个字符booleanfalse
active-iconswitch 状态为 on 时所显示图标,设置此项会忽略 active-textstring | Component
inactive-iconswitch 状态为 off 时所显示图标,设置此项会忽略 inactive-textstring | Component
active-action-iconon 状态下滑块内显示的图标组件string | Component
inactive-action-iconoff 状态下滑块内显示的图标组件string | Component
active-textswitch 打开时的文字描述string
inactive-textswitch 关闭时的文字描述string
active-valueswitch 状态为 on 时的值boolean | string | numbertrue
inactive-valueswitch 状态为 off 时的值boolean | string | numberfalse
nameswitch 对应的 name 属性string
validate-event改变 switch 状态时是否触发表单的校验booleantrue
before-changeswitch 状态改变前的钩子,返回 false 或者返回 Promise 且被 reject 则停止切换() => Promise<boolean> | boolean
idinput 的 idstring
tabindexinput 的 tabindexstring | number
aria-label等价于原生 input aria-label 属性string

Events

事件名说明回调参数
changeswitch 状态发生变化时的回调函数(value: boolean | string | number) => void

Slots

插槽名说明
active-action自定义打开状态下滑块(Action)的内容
inactive-action自定义关闭状态下滑块(Action)的内容
active自定义打开状态下的内容(inline-prompt 模式下在点内,否则在右侧)
inactive自定义关闭状态下的内容(inline-prompt 模式下在点内,否则在左侧)

Expose

名称说明类型
focus使 Switch 获取焦点() => void
checkedSwitch 是否选中ComputedRef<boolean>

主题变量

变量名说明默认值
--yh-switch-on-color开启状态背景色var(--yh-color-primary)
--yh-switch-off-color关闭状态背景色var(--yh-border-color)
--yh-switch-width开关总宽度40px
--yh-switch-height开关总高度20px
--yh-switch-button-size滑块按钮大小16px
--yh-switch-font-size字体大小var(--yh-font-size-base)

Released under the MIT License.