Switch 开关 - Vant 4
Switch 开关
介绍
用于在打开和关闭状态之间进行切换。
引入
通过以下方式来全局注册组件,更多注册方式请参考组件注册。
js
import { createApp } from'vue'; import { Switch } from'vant'; const app = createApp(); app.use(Switch);代码演示
基础用法
通过 v-model 绑定开关的选中状态,true 表示开,false 表示关。
html
js
import { ref } from'vue'; exportdefault { setup() { const checked = ref(true); return { checked }; }, };禁用状态
通过 disabled 属性来禁用开关,禁用状态下开关不可点击。
html
加载状态
通过 loading 属性设置开关为加载状态,加载状态下开关不可点击。
html
自定义大小
通过 size 属性自定义开关的大小。
html
自定义颜色
active-color 属性表示打开时的背景色,inactive-color 表示关闭时的背景色。
html
自定义按钮
通过 node 插槽自定义按钮的内容。
html
异步控制
需要异步控制开关时,可以使用 modelValue 属性和 update:model-value 事件代替 v-model,并在事件回调函数中手动处理开关状态。
html
js
import { ref } from'vue'; import { showConfirmDialog } from'vant'; exportdefault { setup() { const checked = ref(true); constonUpdateValue = (newValue) => { showConfirmDialog({ title: '提醒', message: '是否切换开关?', }).then(() => { checked.value = newValue; }); }; return { checked, onUpdateValue, }; }, };搭配单元格使用
html
API
Props
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| v-model | 开关选中状态 | any | false |
| loading | 是否为加载状态 | boolean | false |
| disabled | 是否为禁用状态 | boolean | false |
| size | 开关按钮的尺寸,默认单位为 px | *number | string* |
| active-color | 打开时的背景色 | string | #1989fa |
| inactive-color | 关闭时的背景色 | string | rgba(120, 120, 128, 0.16) | | active-value | 打开时对应的值 | any | true | | inactive-value | 关闭时对应的值 | any | false |
Events
| 事件名 | 说明 | 回调参数 |
|---|---|---|
| change | 开关状态切换时触发 | value: any |
| click | 点击时触发 | event: MouseEvent |
Slots
| 名称 | 说明 | 参数 |
|---|---|---|
| node | 自定义按钮的内容 | - |
| background | 自定义开关的背景内容 | - |
类型定义
组件导出以下类型定义:
ts
importtype { SwitchProps } from'vant';主题定制
样式变量
组件提供了下列 CSS 变量,可用于自定义样式,使用方法请参考 ConfigProvider 组件。
| 名称 | 默认值 | 描述 |
|---|---|---|
| --van-switch-size | 26px | - |
| --van-switch-width | calc(1.8em + 4px) | - |
| --van-switch-height | calc(1em + 4px) | - |
| --van-switch-node-size | 1em | - |
| --van-switch-node-background | var(--van-white) | - |
| --van-switch-node-shadow | 0 3px 1px 0 rgba(0, 0, 0, 0.05) | - |
| --van-switch-background | rgba(120, 120, 128, 0.16) | - |
| --van-switch-on-background | var(--van-primary-color) | - |
| --van-switch-duration | var(--van-duration-base) | - |
| --van-switch-disabled-opacity | var(--van-disabled-opacity) | - |