Switch

Switch is used to represent switching between two states (e.x on-off)

Examples

Basic

Basic switch usage

<Switch bind:checked on:change="{onChange}" />

<script>
  import { Switch } from "svant";

  let checked = true;

  function onChange({ detail: checked }) {
    console.log(`switch to ${checked}`);
  }
</script>

Disabled

Disable state of switch


<Switch {disabled} bind:checked />
<br />
<Button type="primary" on:click="{toggle}" style="{{ marginTop: '16px' }}">
  Toggle disabled
</Button>

<script>
  import { Button, Switch } from "svant";
  let checked = true;
  let disabled = true;
  function onChange({ detail: checked }) {
    console.log(`switch to ${checked}`);
  }
  function toggle() {
    disabled = !disabled;
  }
</script>

Using Slots

How to use slots to set values for checked/unchecked state



<Switch bind:checked="{checked1}">
  <span slot="checked">ON</span>
  <span slot="unchecked">OFF</span>
</Switch>
<br />
<Switch bind:checked="{checked2}">
  <span slot="checked">1</span>
  <span slot="unchecked">0</span>
</Switch>
<br />
<Switch bind:checked="{checked3}">
  <div slot="checked">
    <CheckOutlined />
  </div>
  <div slot="unchecked">
    <CloseOutlined />
  </div>
</Switch>

<script>
  import { Button, Switch } from "svant";
  import { CheckOutlined, CloseOutlined } from "svant/icons";

  let checked1 = true;
  let checked2 = true;
  let checked3 = true;
</script>

Switch size

Switches can be either the default size or small


<div>
  <Switch bind:checked="{checked1}" />
  <br />
  <Switch size="small" bind:checked="{checked2}" />
</div>

<script>
  import { Switch } from "svant";
  let checked1 = true;
  let checked2 = true;
</script>

Loading

Loading state of the switch


<Switch loading bind:checked="{checked1}" />
<br />
<Switch bind:checked="{checked2}" size="small" loading />

<script>
  import { Button, Switch } from "svant";
  let checked1 = true;
  let checked2 = false;
</script>

API

Attributes

PropertyDescriptionTypeDefault
autoFocusGet focus when component mounted.Booleanfalse
checkedDetermine whether the Switch is checked. This property can be used for 2 way binding.Booleanfalse
disabledDisables the SwitchBooleanfalse
loadingShows loading for the SwitchBooleanfalse
sizeThe size of the Switch, options: `default` `small`Stringdefault

Events

NameDescription
changeTriggers when the switch value changes.
clickTriggers when the switch is clicked.

Bind

NameDescription
focusLet's you bind to the button focus method.
blurLet's you bind to the button blur method.

Slots

NameDescription
checkedUsed to define what to show when the switch is checked.
uncheckedUsed to define what to show when the switch is unchecked.