Switch
A binary switch with custom values, loading and disabled states, shape and size options, labels, keyboard operation, and form integration.
Import
import { HuiSwitch } from '@nscode/handy-ui'
import type {
SwitchProps,
SwitchEmits,
SwitchExpose,
SwitchSize,
SwitchShape
} from '@nscode/handy-ui'
String business values
modelValue, activeValue and inactiveValue preserve string values, including empty strings and strings matching the prop name. Use explicit bindings such as :active-value="true" for boolean business values; active-value="" represents an empty string. The boolean props disabled and loading retain their usual behavior.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSwitch, HuiSpace } from '@nscode/handy-ui'
const activeEmpty = ref<string | number | boolean>('off')
const inactiveEmpty = ref<string | number | boolean>('on')
const last = ref('No notification yet')
</script>
<template>
<HuiSpace direction="vertical" fill class="switch-value-demo">
<HuiSpace wrap>
<HuiSwitch
v-model="activeEmpty"
class="switch-empty-active"
active-value=""
inactive-value="off"
aria-label="Empty string active value"
@change="last = JSON.stringify($event)"
/>
<span class="switch-active-result"
>Empty string active value:{{ JSON.stringify(activeEmpty) }}</span
>
</HuiSpace>
<HuiSpace wrap>
<HuiSwitch
v-model="inactiveEmpty"
class="switch-empty-inactive"
active-value="on"
inactive-value=""
aria-label="Empty string inactive value"
@change="last = JSON.stringify($event)"
/>
<span class="switch-inactive-result"
>Empty string inactive value:{{ JSON.stringify(inactiveEmpty) }}</span
>
</HuiSpace>
<HuiSwitch
class="switch-controlled-empty"
:model-value="''"
aria-label="An empty string is not boolean true"
/>
<span>A fixed empty string does not equal the default active value true</span>
<span class="switch-string-notice">Latest notification: {{ last }}</span>
</HuiSpace>
</template>
Internal state and controlled updates
An omitted value starts at false. Explicit undefined remains controlled and is interpreted as false. Omitting the prop, including when only listening for updates, uses internal state that survives unrelated parent renders. A passed prop remains controlled; rejecting an update preserves the parent value. Switching modes reports a development warning. No defaultValue prop is added.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSwitch, HuiButton, HuiSpace } from '@nscode/handy-ui'
const q1Redraw = ref(0)
const q1Last = ref('No request')
const q1Model = ref(false)
</script>
<template>
<div class="q1-state-demo switch-q1-demo">
<HuiButton class="q1-redraw" @click="q1Redraw++">Parent redraw {{ q1Redraw }}</HuiButton>
<HuiSpace direction="vertical" fill>
<div>
<p>Omitted prop: internal state</p>
<div class="q1-local"><HuiSwitch /></div>
</div>
<div>
<p>Update listener only: internal state</p>
<div class="q1-listener"><HuiSwitch @update:model-value="q1Last = String($event)" /></div>
</div>
<div>
<p>Explicit undefined: controlled</p>
<div class="q1-empty"><HuiSwitch :model-value="undefined" /></div>
</div>
<div>
<p>Fixed controlled value: parent rejects</p>
<div class="q1-fixed">
<HuiSwitch :model-value="true" @update:model-value="q1Last = String($event)" />
</div>
</div>
<div>
<p>Two-way binding</p>
<div class="q1-bound"><HuiSwitch v-model="q1Model" /></div>
</div>
<p class="q1-notification">Bound value: {{ q1Model }}; latest request: {{ q1Last }}</p>
</HuiSpace>
</div>
</template>
Examples
Binding, Disabled, and Loading
A switch is on only when its model strictly equals active-value. Disabled switches cannot receive focus. Loading switches remain focusable but ignore pointer and keyboard toggles.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const value = ref(false)
</script>
<template>
<HuiSpace wrap>
<HuiSwitch v-model="value" aria-label="Enabled" />
<HuiSwitch :model-value="false" disabled aria-label="Disabled off" />
<HuiSwitch :model-value="true" disabled aria-label="Disabled on" />
<HuiSwitch :model-value="false" loading aria-label="Loading off" />
<HuiSwitch :model-value="true" loading aria-label="Loading on" />
<span>Value: {{ value }}</span>
</HuiSpace>
</template>
Wait for an Application Request
beforeChange receives the target value before an update. Only false, a thrown error, or a rejected promise blocks the toggle; true and undefined allow it. Async checks show loading automatically and ignore repeated clicks and key presses.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const value = ref(false)
const rejectNext = ref(false)
const status = ref('Waiting')
const save = async (next: string | number | boolean) => {
const rejected = rejectNext.value
status.value = 'Saving'
await new Promise<void>((resolve) => window.setTimeout(resolve, 500))
if (rejected) {
status.value = 'Rejected; previous value retained'
return false
}
status.value = next === true ? 'Enabled' : 'Disabled'
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiSwitch v-model="value" :before-change="save" aria-label="Save setting" />
<HuiButton @click="rejectNext = !rejectNext">
Next toggle: {{ rejectNext ? 'reject' : 'allow' }}
</HuiButton>
<span>Bound value: {{ value }}</span>
</HuiSpace>
<span>{{ status }}</span>
</HuiSpace>
</template>
Application confirmation can run inside the hook; return false when cancelled. The component does not open a confirmation dialog. The hook can be written inline in the template (for example :before-change="() => toggle(row)" in a table row); parent re-renders while it is pending do not affect the result.
Sizes, Shapes, and Labels
Large/default/small tracks measure 44x22, 36x18, and 28x14px. Round is capsule-shaped; square uses rounded corners. Inactive text appears on the left and active text on the right. Omitted size inherits form/provider settings.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import type { SwitchSize } from '@nscode/handy-ui'
const sizes: SwitchSize[] = ['large', 'default', 'small']
const value = ref(false)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace v-for="size in sizes" :key="size" wrap>
<span>{{ size }}</span>
<HuiSwitch v-model="value" :size="size" shape="round" aria-label="Round switch" />
<HuiSwitch v-model="value" :size="size" shape="square" aria-label="Square switch" />
<HuiSwitch v-model="value" :size="size" active-text="On" inactive-text="Off" />
</HuiSpace>
</HuiSpace>
</template>
Custom String and Numeric Values
Types are significant: numeric 1 and string '1' differ. An unrecognized model value appears off; the next user toggle emits active-value.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const status = ref<string | number | boolean>('off')
const numeric = ref<string | number | boolean>(0)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSwitch
v-model="status"
active-value="on"
inactive-value="off"
active-text="Enabled"
inactive-text="Disabled"
/>
<HuiSwitch
v-model="numeric"
:active-value="1"
:inactive-value="0"
active-text="1"
inactive-text="0"
/>
<span>Values: {{ status }}, {{ numeric }}</span>
</HuiSpace>
</template>
Keyboard, Events, and Focus Methods
Tab focuses an enabled switch. Enter/Space toggles it once per key press; held key repeats are ignored. A user toggle emits update before change. Programmatic parent changes emit no change event. Focus/blur only reports entering/leaving the component.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import type { SwitchExpose } from '@nscode/handy-ui'
const control = ref<SwitchExpose>()
const value = ref(false)
const event = ref('Waiting')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @mousedown.prevent @click="control?.focus()">focus()</HuiButton>
<HuiButton @mousedown.prevent @click="control?.blur()">blur()</HuiButton>
</HuiSpace>
<HuiSwitch
ref="control"
v-model="value"
active-text="On"
inactive-text="Off"
@change="event = 'change: ' + $event"
@focus="event = 'focus'"
@blur="event = 'blur'"
/>
<span>{{ event }}</span>
</HuiSpace>
</template>
Form Integration
<script setup lang="ts">
import { reactive } from 'vue'
import { HuiForm, HuiFormItem, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import type { FormRule } from '@nscode/handy-ui'
const model = reactive({ enabled: false })
const rules: Record<string, FormRule[]> = {
enabled: [{ validator: (value) => value === true || 'Enable this setting', trigger: 'change' }]
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiForm :model="model" :rules="rules"
><HuiFormItem label="Enabled" prop="enabled"
><HuiSwitch v-model="model.enabled" /></HuiFormItem
></HuiForm>
<HuiSwitch :model-value="false" :validate-event="false" aria-label="No automatic validation" />
</HuiSpace>
</template>
Inline labels and state slots
inlinePrompt renders only the current state inside the track, including small switches. Long labels expand the track naturally while the thumb stays at its ends with an animated transition. The active/inactive slots take precedence over the matching text props; without inlinePrompt, both slots appear beside the track. Empty slots use Vue's text fallback.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiIcon, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const value = ref(false)
const inline = ref(true)
const sizes = ['large', 'default', 'small'] as const
</script>
<template>
<HuiSpace class="switch-inline-demo" direction="vertical" fill>
<HuiSpace wrap>
<div v-for="size in sizes" :key="size">
<span>{{ size }}:</span>
<HuiSwitch
v-model="value"
:size="size"
inline-prompt
active-text="On"
inactive-text="Off"
aria-label="Enable account"
/>
</div>
</HuiSpace>
<HuiSwitch
inline-prompt
active-text="Allow publishing"
inactive-text="Waiting for administrator approval"
aria-label="Allow publishing"
/>
<HuiSpace wrap>
<HuiSwitch
:model-value="true"
inline-prompt
loading
active-text="On"
inactive-text="Off"
aria-label="Loading enabled state"
/>
<HuiSwitch
:model-value="false"
inline-prompt
loading
active-text="On"
inactive-text="Off"
aria-label="Loading disabled state"
/>
<HuiSwitch
:model-value="true"
inline-prompt
disabled
active-text="On"
aria-label="Disabled control"
/>
</HuiSpace>
<HuiButton class="inline-placement-toggle" @click="inline = !inline"
>Move slot content inside or outside</HuiButton
>
<HuiSwitch
v-model="value"
class="inline-slots"
:inline-prompt="inline"
active-text="Label fallback"
inactive-text="Label fallback"
aria-label="Icon status"
>
<template #active
><HuiSpace :size="4"
><HuiIcon name="check" size="xs" /><span>Available</span></HuiSpace
></template
>
<template #inactive
><HuiSpace :size="4"
><HuiIcon name="close" size="xs" /><span>Paused</span></HuiSpace
></template
>
</HuiSwitch>
<span class="inline-status">Current: {{ value }}; inline slots: {{ inline }}</span>
</HuiSpace>
</template>
Inline content is aria-hidden and does not replace the switch's stable accessible name. Provide aria-label or a form label. Loading keeps the current label and the spinner inside the thumb; asynchronous guards and controlled parent acceptance retain their existing behavior.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| modelValue | boolean | string | number | undefined | Value, checked when strictly equal to activeValue. Omit it for internal state starting at false; a passed prop, including undefined, is controlled. |
| disabled | boolean | false | Disable interaction and focus |
| loading | boolean | false | External progress, combined with the pending hook state; block toggles and retain focus |
| beforeChange | (newValue: boolean | string | number) => boolean | void | Promise<boolean | void> | — | Check the target value; only false, a thrown error, or a rejected promise blocks it. Async checks show loading and ignore repeated actions. |
| size | 'large' | 'default' | 'small' | — | Inherited size |
| shape | 'round' | 'square' | 'round' | Capsule or rounded rectangle |
| inlinePrompt | boolean | false | Render the current text or state slot inside the track; all sizes supported. |
| activeText | string | '' | Right-side label |
| inactiveText | string | '' | Left-side label |
| activeValue | boolean | string | number | true | Value emitted when switching on |
| inactiveValue | boolean | string | number | false | Value emitted when switching off |
| validateEvent | boolean | true | Validate when the model changes |
Events
| Event | Payload | Description |
|---|---|---|
| update:modelValue | (value: boolean | string | number) | User toggle requests a new value after the hook allows it |
| change | (value: boolean | string | number) | Follows update:modelValue with the target value; controlled parents may reject the update |
| focus | (event: FocusEvent) | Focus enters the component |
| blur | (event: FocusEvent) | Focus leaves the component |
Slots
| Slot | Description |
|---|---|
| active | Replaces activeText; right-side content, or current on-state content inside the track |
| inactive | Replaces inactiveText; left-side content, or current off-state content inside the track |
Methods
| Name | Type | Description |
|---|---|---|
| focus | () => void | Focus the current or first available control unless disabled or unmounted |
| blur | () => void | Blur only an active element inside this component in its owner document |
Types
import type {
SwitchSize,
SwitchEmits,
SwitchShape,
SwitchProps,
SwitchExpose,
SwitchSlots
} from '@nscode/handy-ui'
export type SwitchSize = 'large' | 'default' | 'small'
export interface SwitchEmits {
'update:modelValue': [value: string | number | boolean]
change: [value: string | number | boolean]
focus: [event: FocusEvent]
blur: [event: FocusEvent]
}
export type SwitchShape = 'round' | 'square'
export interface SwitchProps {
modelValue?: string | number | boolean
disabled?: boolean
loading?: boolean
beforeChange?: (newValue: string | number | boolean) => boolean | void | Promise<boolean | void>
size?: SwitchSize
shape?: SwitchShape
activeText?: string
inactiveText?: string
inlinePrompt?: boolean
activeValue?: string | number | boolean
inactiveValue?: string | number | boolean
validateEvent?: boolean
}
export interface SwitchExpose {
focus: () => void
blur: () => void
}