Skip to content

Switch 开关

介绍

用来打开或关闭选项。

基础用法

html
<template>
  <nut-switch v-model="checked"></nut-switch>
</template>
ts
const checked = ref(true);

禁用状态

html
<template>
  <nut-switch v-model="checked" disabled></nut-switch>
</template>

加载状态

html
<template>
  <nut-switch v-model="checked" loading></nut-switch>
</template>

change事件

html
<template>
  <nut-switch v-model="checked" @change="onChange"></nut-switch>
</template>
ts
const checked = ref(true);

function onChange(value: boolean) {
  console.log("change", value);
}

异步控制

需要异步控制开关时,可以使用 model-value 属性和 update:model-value 事件代替 v-model, 并在事件回调函数中手动处理开关状态。

html
<template>
  <nut-switch :model-value="checked" @update:model-value="onUpdate"></nut-switch>
</template>
ts
const checked = ref(true);

function onUpdate(value: boolean) {
  uni.showModal({
    title: "提示",
    content: "是否切换开关?",
    success({ confirm }) {
      if (confirm) {
        checked.value = value;
      }
    }
  });
}

自定义颜色

html
<template>
  <nut-switch v-model="checked" active-color="blue"></nut-switch>
</template>

支持文字

html
<template>
  <nut-switch
    v-model="checked"
    active-text=""
    inactive-text=""
  ></nut-switch>
</template>

自定义加载图标

html
<template>
  <nut-switch v-model="checked" loading>
    <template #icon>
      <nut-icon name="loading"></nut-icon>
    </template>
  </nut-switch>
</template>

API

Props

参数说明类型可选值默认值
v-model开关状态boolean / string / number-false
disabled禁用状态boolean-false
loading加载状态boolean-false
active-color打开时的背景颜色string-#fa2c19
inactive-color关闭时的背景颜色string-#ebebeb
active-text打开时文字描述string--
inactive-text关闭时文字描述string--
active-value打开时组件的值boolean / string / number-true
inactive-value关闭组件的值boolean / string / number-false

Events

事件名说明类型
change切换开关时触发(value: boolean, event: Event) => void

Slots

名称说明
icon加载状态图标

主题定制

样式变量

组件提供了下列 CSS 变量,可用于自定义样式,使用方法请参考 ConfigProvider 组件

名称默认值
--nut-switch-close-bg-color#ebebeb
--nut-switch-close-cline-bg-color#f0f0f0
--nut-switch-width36px
--nut-switch-height21px
--nut-switch-line-height21px
--nut-switch-border-radius21px
--nut-switch-inside-width13px
--nut-switch-inside-height13px
--nut-switch-inside-open-transformtranslateX(146%)
--nut-switch-inside-close-transformtranslateX(30%)

MIT Licensed