Skip to content

Switch 开关

表示两种相互对立的状态间的切换,多用于触发「开/关」。

基础用法

绑定 v-model 到一个 Boolean 类型的变量。 可以使用 --pr-switch-on-color 属性与 --pr-switch-off-color 属性来设置开关的背景色。

基础Switch
Switch 基础用例
<script setup lang="ts">
import { ref } from 'vue'
import Switch from '@/components/Switch/Switch.vue'
const test = ref(false)
</script>
<template>
  <Switch v-model="test" />
</template>

禁用状态

设置 disabled 属性,接受一个 boolean,设置true即可禁用。

正常:

禁用:
Switch 禁用状态
Switch 禁用状态
<script setup>
import { ref } from 'vue'
import Switch from '@/components/Switch/Switch.vue'
const test = ref(false)
const test2 = ref(false)
</script>
<template>
  正常:<Switch v-model="test" /> <br/>
  禁用:<Switch v-model="test2" disabled/>
</template>

不同尺寸

设置 size 属性,接受large / small,呈现不同的尺寸。

Switch 不同尺寸
Switch 不同尺寸
<script setup>
import { ref } from 'vue'
import Switch from '@/components/Switch/Switch.vue'
const test = ref(false)
</script>
<template>
  <div class="switch-size-container">
    <Switch v-model="test" size="large"/>
    <Switch v-model="test"/>
    <Switch v-model="test" size="small"/>
  </div>
</template>
<style scoped>
.switch-size-container {
  display: flex;
  align-items: center;
  .vk-switch {
    margin-right: 10px;
  }
}
</style>

支持自定义 value 类型

你可以设置 active-valueinactive-value 属性, 它们接受 boolean | string | number 类型的值。

model-value: right

支持自定义 value 类型
Switch 支持自定义 value 类型
<script setup lang="ts">
import { ref } from 'vue'
import Switch from '@/components/Switch/Switch.vue'
const test = ref('right')
</script>
<template>
  <Switch v-model="test" activeValue="right" inactiveValue="wrong"/>
  <h4>model-value: {{test}}</h4>
</template>

文字描述

使用 active-text 属性与 inactive-text 属性来设置开关的文字描述。

OFF
支持文字描述
Switch 文字描述
<script setup>
import { ref } from 'vue'
import Switch from '@/components/Switch/Switch.vue'
const test = ref(false)
</script>
<template>
  <Switch v-model="test" activeText="ON" inactiveText="OFF"/>
</template>

API

Switch Attributes

参数说明类型默认值
modelValue绑定值boolean | string | numberfalse
disabled是否禁用booleanfalse
activeText打开状态文本string-
inactiveText关闭状态文本string-
activeValue打开时对应值boolean | string | numbertrue
inactiveValue关闭时对应值boolean | string | numberfalse
name原生 name 属性string-
id原生 id 属性string-
size尺寸'small' | 'large'-

Switch Events

事件名说明回调参数
update:modelValue绑定值变化时触发(value: boolean | string | number) => void
change状态切换时触发(value: boolean | string | number) => void