Components/Switch

Switch

A control that toggles between on and off states.

VerifiedSince 0.3.4

Usage

EXAMPLE.VUE
<script setup lang="ts">
import { ref } from 'vue'

const enabled = ref(true)
</script>

<template>
  <TuffSwitch v-model="enabled" />
</template>

Toggle State

Click, Enter, or Space toggles the switch.

Loading demo...

Sizes

size also sets the label's font size and gap.

Loading demo...

Disabled

Loading demo...

Loading

Set loading while a server confirms the change. The thumb stays on the old value as a spinning ring, and toggling is blocked.

Loading demo...

Labels

A changing label crossfades; labelPlacement puts it before or after the track. The default slot renders as-is, without the transition.

Loading demo...

Custom Colors

Override --tuff-switch-active-color, --tuff-switch-track-color, or --tuff-switch-thumb-color.

Loading demo...

Settings Row

When state text sits outside the switch, render it with TxTextTransformer to get the same transition.

Loading demo...

Best Practices

  • Use a switch for settings that apply immediately; use a checkbox for values submitted with a form.
  • When the server must confirm, set loading and write modelValue only on success. On failure, just clear loading.
  • Put the control's name in label ("Compact mode"). Keep state text such as "On" outside, rendered with TxTextTransformer, so it isn't announced twice.
  • Recolor through the CSS variables, not by rewriting .tuff-switch__track rules.

API Reference

Props

PropTypeDefaultDescription
modelValuebooleanfalseThe on/off state, bound with v-model.
labelstring-Text beside the track; crossfades when it changes.
labelPlacement'start' | 'end''end'Puts the label before or after the track.
size'small' | 'default' | 'large''default'Size; also sets the label's font size and gap.
disabledbooleanfalseBlocks toggling and removes the switch from the tab order.
loadingbooleanfalseShows a spinning ring and blocks toggling.

Events

EventParamsDescription
update:modelValue(value: boolean) => voidFires after a user toggle with the new value.
change(value: boolean) => voidFires together with update:modelValue.

Slots

SlotPropsDescription
default-Custom label content; overrides label and renders without the transition.

Overview

  • The root is a native <button role="switch"> with aria-checked.
  • It is controlled: a toggle only emits, and the switch updates once the parent writes modelValue back.
  • disabled and loading both set the native disabled attribute; loading keeps full opacity and sets aria-busy="true".
  • With visible text (label or the slot), no aria-label is rendered.
  • Under reduced motion, the loading ring stops spinning.

Technologies

  • The state classes is-active, is-disabled, is-loading, and has-label sit on the root; the track and thumb are .tuff-switch__track and .tuff-switch__thumb.
  • Source: packages/tuffex/packages/components/src/switch/.
查看源码
packages/tuffex/packages/components/src/switch/index.ts