--- title: Switch 开关 description: 用于切换单个状态的即时开关 --- # Switch 开关 `Switch` 表示「开 / 关」两态,通常**立即生效**(不需要点保存)。 ## 何时使用 - 设置项里即时生效的开关(启用通知、公开可见); - 表格行内的状态切换; - 需要注意:`Switch` 不是复选框的替代品。多个选项之间互不排斥、需要一起提交时用 [Checkbox](/ui/form/checkbox)。 ## 基础用法 `v-model` 绑定 `boolean`;`change` 回传新值与原生事件。 :::demo{name="switch/basic"} ::: ## 禁用态 :::demo{name="switch/disabled"} ::: ## 与表单一起使用 放入 `G3FormItem` 时,label 与校验由表单负责,`Switch` 只提供值。 :::demo{name="switch/in-form"} ::: ## 关于「异步切换」 组件本身不做 loading/回滚,因为「乐观切换 + 失败回滚」的业务语义差异很大。推荐在 `change` 里显式处理: ```ts async function onChange(next: boolean) { const previous = !next try { await api.update(next) } catch { enabled.value = previous // 失败回滚 G3Message.error('保存失败') } } ``` ## API ### Props | 名称 | 类型 | 默认值 | 说明 | | --- | --- | --- | --- | | `modelValue` | `boolean` | `false` | 双向绑定的开关状态 | | `disabled` | `boolean` | `false` | 禁用态 | ### Events | 名称 | 参数 | 说明 | | --- | --- | --- | | `update:modelValue` | `(value: boolean)` | 状态变化 | | `change` | `(value: boolean, event: MouseEvent)` | 同上,附带原生点击事件 | ### Slots | 名称 | 参数 | 说明 | | --- | --- | --- | | `default` | — | 开关旁的文案(可点击切换) | ### 类型定义 ```ts export interface SwitchProps { modelValue?: boolean disabled?: boolean } ``` ### 样式变量 | 变量 | 默认值 | 说明 | | --- | --- | --- | | `--g3-switch-width` | `32px` | 轨道宽 | | `--g3-switch-height` | `18px` | 轨道高 | | `--g3-switch-thumb-size` | `14px` | 滑块直径 | | `--g3-switch-thumb-offset` | `2px` | 滑块内边距 | | `--g3-color-primary` | `#18181b` | 开启态轨道色 | ## 实现说明 - 没有原生的 ``,因此用 `