Switch - Vant 4
Switch
Intro
Used to switch between open and closed states.
Install
Register component globally via app.use, refer to Component Registration for more registration ways.
js
import { createApp } from'vue'; import { Switch } from'vant'; const app = createApp(); app.use(Switch);Usage
Basic Usage
html
js
import { ref } from'vue'; exportdefault { setup() { const checked = ref(true); return { checked }; }, };Disabled
html
Loading
html
Custom Size
html
Custom Color
html
Custom Node
Using node slot to custom the content of the node.
html
Async Control
html
js
import { ref } from'vue'; import { showConfirmDialog } from'vant'; exportdefault { setup() { const checked = ref(true); constonUpdateValue = (newValue) => { showConfirmDialog({ title: 'Confirm', message: 'Are you sure to toggle switch?', }).then(() => { checked.value = newValue; }); }; return { checked, onUpdateValue, }; }, };Inside a Cell
html
API
Props
| Attribute | Description | Type | Default |
|---|---|---|---|
| v-model | Check status of Switch | *ActiveValue | InactiveValue* |
| loading | Whether to show loading icon | boolean | false |
| disabled | Whether to disable switch | boolean | false |
| size | Size of switch button | *number | string* |
| active-color | Background color when active | string | #1989fa |
| inactive-color | Background color when inactive | string | rgba(120, 120, 128, 0.16) | | active-value | Value when active | any | true | | inactive-value | Value when inactive | any | false |
Events
| Event | Description | Parameters |
|---|---|---|
| change | Emitted when check status changed | value: any |
| click | Emitted when component is clicked | event: MouseEvent |
Slots
| Name | Description | SlotProps |
|---|---|---|
| node | Custom the content of node | - |
| background | Custom the background of switch | - |
Types
The component exports the following type definitions:
ts
importtype { SwitchProps } from'vant';Theming
CSS Variables
The component provides the following CSS variables, which can be used to customize styles. Please refer to ConfigProvider component.
| Name | Default Value | Description |
|---|---|---|
| --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) | - |