Skip to content

Switch 开关

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

基础用法

可以使用一个 v-model 绑定开关的选中状态。默认情况下,Switch 的选中状态为 false,且绑定的值为布尔值。

<template>
    <ym-switch v-model="value"></ym-switch>
</template>

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

const value = ref(false)
</script>

开关尺寸

可以使用 size 属性来定义开关的大小,默认不用书写,可选值为 small ,large

<template>
    <div class="container">
        <ym-switch size="small"></ym-switch>
        <ym-switch ></ym-switch>
        <ym-switch size="large"></ym-switch>
    </div>
</template>
<style scoped>
.container  {
    display: flex;
    align-items: center;
    gap: 20px;
}

</style>

文字描述

可以使用 activeTextinactiveText 属性来定义开关打开或关闭时的文字描述。

关闭

<template>
    <ym-switch size="large" activeText="开启" inactiveText="关闭"></ym-switch>
</template>

自定义Value

可以使用 activeValueinactiveValue 属性来自定义激活时的值。

<template>
    <ym-switch size="large" v-model="value" :activeValue="1" :inactiveValue="0" @change="handleChange"></ym-switch>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { YmMessage } from 'guyan-ym-ui';

const value = ref(0)

const handleChange = (val: number) => {
    YmMessage.info('开关状态:' + val)
}
</script>

禁用状态

可以使用 disabled 属性来定义开关打开或关闭时的文字描述。

<template>
    <div class="container">
        <ym-switch size="small" disabled></ym-switch>
        <ym-switch disabled></ym-switch>
        <ym-switch size="large" disabled></ym-switch>
    </div>
</template>
<style scoped>
.container  {
    display: flex;
    align-items: center;
    gap: 20px;
}

</style>

Switch API

Props

NameDescriptionTypeDefault
v-model绑定value值boolean-
disabled是否禁用booleanfalse
size尺寸enum- small | large-
activeText激活时文字string-
inactiveText未激活文字string-
activeValue自定义激活时的值boolean | string | number
inactiveValue自定义未激活时的值boolean | string | number-
name原生namestring-

Events

NameDescriptionType
update:modelValue绑定值改变时触发(visible: boolean) => void
change绑定值改变时触发(visible: boolean) => void

Expose

NameDescriptionType
checked当前是否选中boolean
focus聚焦() => void