Skip to content

Switch 开关

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

基础用法

通过标签 <NueSwitch> 声明一个开关组件。

通过 v-model 为开关组件绑定一个响应式值。

<template>
    <nue-div align="center">
        <nue-switch v-model="state"></nue-switch>
        <nue-text>{{ state ? '开' : '关' }}</nue-text>
    </nue-div>
</template>

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

const state = ref(false);
</script>

大小

通过属性 size 设置开关组件的大小,可选值为 smalllarge,不指定则为默认大小。

<template>
    <nue-div align="center">
        <nue-switch v-model="state" size="small"></nue-switch>
        <nue-switch v-model="state" size="large"></nue-switch>
    </nue-div>
</template>

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

const state = ref(false);
</script>

状态文字描述

通过属性 show-text 设置开关描述文字是否显示。

通过属性 active-textinactive-text 设置开关的描述文字。属性接受 string 类型值,开关状态默认值分别为 I 和 O。

<template>
    <nue-div align="center">
        <nue-switch v-model="state1" show-text />
        <nue-switch v-model="state2" active-text="当前为开" inactive-text="状态:关" show-text />
    </nue-div>
</template>

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

const state1 = ref(false);
const state2 = ref(false);
</script>

禁用状态

通过属性 disabled 设置开关组件的禁用状态。

<template>
    <nue-div align="center">
        <nue-switch v-model="state1" disabled />
        <nue-switch v-model="state2" disabled />
    </nue-div>
</template>

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

const state1 = ref(false);
const state2 = ref(true);
</script>

加载态 & 状态切换前的回调函数

通过属性 loading 设置开关组件的加载状态。属性 loading 通常与状态切换前回调函数 before-switch 搭配使用。在 before-switch 回调函数中,只有返回 Resolved Promise 或是 ture 时才会使开关组件的状态发生改变。

<template>
    <nue-switch
        v-model="state"
        show-text
        active-text="点击关闭"
        inactive-text="点击打开"
        :loading="loading"
        :before-switch="handleBeforeSwitch"
    />
</template>

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

const state = ref(false);
const loading = ref(false);

const handleBeforeSwitch = async () => {
    loading.value = true;
    await new Promise(resolve => setTimeout(resolve, 1000));
    loading.value = false;
    return true;
};
</script>

注意事项

  1. 双向绑定:使用 v-model 绑定布尔值,实现双向数据同步。
  2. 异步切换beforeSwitch 回调函数支持返回 Promise,可用于处理异步操作(如 API 请求)。
  3. 加载状态loading 状态时组件会自动禁用,防止用户重复操作。
  4. 状态文字showText 需要设置为 true 才能显示 activeTextinactiveText

组件属性与事件

下方涵盖了 NueSwitch 组件所有的可用属性与事件。

属性

属性Type默认值说明
modelValueboolean-绑定值
size'small' | 'normal' | 'large'-尺寸
disabledbooleanfalse是否禁用
loadingbooleanfalse加载状态
loadingIconstring-加载图标
showTextbooleanfalse显示状态文字
activeTextstring-开启状态显示的文字
inactiveTextstring-关闭状态显示的文字
beforeSwitch(value: boolean) => Promise<boolean>-切换前回调,返回 false 可阻止切换
themestring | string[] | Record<string, boolean>-主题样式(继承自 GlobalProps)

事件

事件参数说明
update:modelValuevalue: boolean值更新事件
changevalue: boolean状态变化事件

Released under the MIT License.