Switch 开关
在“开”和“关”两个状态之间切换,点击后立即生效的设置项用它。
引入
import { HuiSwitch } from '@nscode/handy-ui'
字符串业务值
modelValue、activeValue、inactiveValue 保留字符串原值,包括空字符串和与属性名相同的字符串。布尔业务值使用 :active-value="true" 等显式绑定,active-value="" 表示空字符串。disabled、loading 等布尔状态属性仍按原规则使用。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSwitch, HuiSpace } from '@nscode/handy-ui'
const activeEmpty = ref<string | number | boolean>('off')
const inactiveEmpty = ref<string | number | boolean>('on')
const last = ref('尚无通知')
</script>
<template>
<HuiSpace direction="vertical" fill class="switch-value-demo">
<HuiSpace wrap>
<HuiSwitch
v-model="activeEmpty"
class="switch-empty-active"
active-value=""
inactive-value="off"
aria-label="开启值为空字符串"
@change="last = JSON.stringify($event)"
/>
<span class="switch-active-result">开启值为空字符串:{{ JSON.stringify(activeEmpty) }}</span>
</HuiSpace>
<HuiSpace wrap>
<HuiSwitch
v-model="inactiveEmpty"
class="switch-empty-inactive"
active-value="on"
inactive-value=""
aria-label="关闭值为空字符串"
@change="last = JSON.stringify($event)"
/>
<span class="switch-inactive-result"
>关闭值为空字符串:{{ JSON.stringify(inactiveEmpty) }}</span
>
</HuiSpace>
<HuiSwitch
class="switch-controlled-empty"
:model-value="''"
aria-label="空字符串不是布尔true"
/>
<span>固定空字符串与默认开启值 true 不相等</span>
<span class="switch-string-notice">最近通知:{{ last }}</span>
</HuiSpace>
</template>
自持状态与受控回填
开关内部从false开始;显式undefined仍受控,按false判断。 未传属性或仅监听更新时组件自行保存,父无关重绘不重置;传入属性(含undefined)即受控,父不接受更新时显示保持父值。切换模式会输出开发诊断,不新增defaultValue等属性。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSwitch, HuiButton, HuiSpace } from '@nscode/handy-ui'
const q1Redraw = ref(0)
const q1Last = ref('尚无请求')
const q1Model = ref(false)
</script>
<template>
<div class="q1-state-demo switch-q1-demo">
<HuiButton class="q1-redraw" @click="q1Redraw++">父重绘 {{ q1Redraw }}</HuiButton>
<HuiSpace direction="vertical" fill>
<div>
<p>未传属性,自行保存</p>
<div class="q1-local"><HuiSwitch /></div>
</div>
<div>
<p>仅监听更新,仍自行保存</p>
<div class="q1-listener"><HuiSwitch @update:model-value="q1Last = String($event)" /></div>
</div>
<div>
<p>显式undefined,父值优先</p>
<div class="q1-empty"><HuiSwitch :model-value="undefined" /></div>
</div>
<div>
<p>固定受控,父拒绝更新</p>
<div class="q1-fixed">
<HuiSwitch :model-value="true" @update:model-value="q1Last = String($event)" />
</div>
</div>
<div>
<p>双向绑定</p>
<div class="q1-bound"><HuiSwitch v-model="q1Model" /></div>
</div>
<p class="q1-notification">绑定值:{{ q1Model }};最近请求:{{ q1Last }}</p>
</HuiSpace>
</div>
</template>
基础用法
用 v-model 绑定一个布尔值。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSwitch } from '@nscode/handy-ui'
const value = ref(false)
</script>
<template>
<HuiSwitch v-model="value" />
<p style="margin-top: 12px">绑定值:{{ value }}</p>
</template>
禁用
disabled 禁用后不能点击,也不能用 Tab 键聚焦。打开、关闭两种状态和带文字的开关都有对应的禁用样式。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const off = ref(false)
const on = ref(true)
</script>
<template>
<HuiSpace wrap>
<HuiSwitch v-model="off" disabled />
<HuiSwitch v-model="on" disabled />
<HuiSwitch v-model="on" shape="square" disabled />
<HuiSwitch v-model="on" active-text="开启" inactive-text="关闭" disabled />
</HuiSpace>
</template>
加载状态
loading 为 true 时圆钮上显示转圈,这期间点击和按键都不会切换。打开、关闭时都能加载。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const on = ref(true)
const off = ref(false)
</script>
<template>
<HuiSpace wrap>
<HuiSwitch v-model="on" loading />
<HuiSwitch v-model="off" loading />
<HuiSwitch v-model="on" shape="square" loading />
</HuiSpace>
</template>
切换前先请求接口
beforeChange 接收目标值,检查通过后才更新开关。返回 false、抛错或 Promise 拒绝时保留原值;返回 true 或 undefined 都放行。异步等待时自动显示加载状态,重复点击或按键不会再次请求。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const value = ref(false)
const rejectNext = ref(false)
const status = ref('等待操作')
const save = async (next: string | number | boolean) => {
const rejected = rejectNext.value
status.value = '正在保存'
await new Promise<void>((resolve) => window.setTimeout(resolve, 500))
if (rejected) {
status.value = '已拒绝,保留原值'
return false
}
status.value = next === true ? '已开启' : '已关闭'
// 没有返回值也放行,无需再手动修改value。
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiSwitch v-model="value" :before-change="save" aria-label="保存开关设置" />
<HuiButton @click="rejectNext = !rejectNext">
下一次{{ rejectNext ? '拒绝' : '允许' }}
</HuiButton>
<span>绑定值:{{ value }}</span>
</HuiSpace>
<span>{{ status }}</span>
</HuiSpace>
</template>
业务需要确认时,可在钩子内等待确认结果,取消时返回 false。组件不会内置确认弹窗。钩子可以在模板里内联写(如表格行里 :before-change="() => toggle(row)"),等待期间父组件重绘不影响结果。
尺寸
size 有 large、default、small 三种,轨道分别是 44×22、36×18、28×14 像素。不写时跟随所在的 HuiFormItem、HuiForm、HuiConfigProvider,都没有时是 default。
下面每一行是一种尺寸:关闭、打开、加载中、方形、带文字。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const off = ref(false)
const on = ref(true)
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">large</span>
<HuiSwitch v-model="off" size="large" />
<HuiSwitch v-model="on" size="large" />
<HuiSwitch v-model="on" size="large" loading />
<HuiSwitch v-model="on" size="large" shape="square" />
<HuiSwitch v-model="on" size="large" active-text="开" inactive-text="关" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">default</span>
<HuiSwitch v-model="off" />
<HuiSwitch v-model="on" />
<HuiSwitch v-model="on" loading />
<HuiSwitch v-model="on" shape="square" />
<HuiSwitch v-model="on" active-text="开" inactive-text="关" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">small</span>
<HuiSwitch v-model="off" size="small" />
<HuiSwitch v-model="on" size="small" />
<HuiSwitch v-model="on" size="small" loading />
<HuiSwitch v-model="on" size="small" shape="square" />
<HuiSwitch v-model="on" size="small" active-text="开" inactive-text="关" />
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
形状
shape 默认是 round,轨道两端是半圆(胶囊形);square 是圆角长方形,轨道和圆钮都是小圆角。三种尺寸都能用。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const off = ref(false)
const on = ref(true)
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">round</span>
<HuiSwitch v-model="off" />
<HuiSwitch v-model="on" size="large" />
<HuiSwitch v-model="on" />
<HuiSwitch v-model="on" size="small" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">square</span>
<HuiSwitch v-model="off" shape="square" />
<HuiSwitch v-model="on" shape="square" size="large" />
<HuiSwitch v-model="on" shape="square" />
<HuiSwitch v-model="on" shape="square" size="small" />
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
文字描述
inactive-text 显示在开关左边,active-text 显示在右边。两段文字一直都在:关闭时左边那段是正文色、右边变淡,打开时右边那段是主色、左边变淡。可以只写其中一个。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const value = ref(false)
const notify = ref(true)
const dark = ref(false)
</script>
<template>
<HuiSpace wrap size="large">
<HuiSwitch v-model="value" active-text="开启" inactive-text="关闭" />
<HuiSwitch v-model="notify" active-text="接收通知" />
<HuiSwitch v-model="dark" inactive-text="暗色主题" />
</HuiSpace>
</template>
轨道文字与状态插槽
inlinePrompt 将当前状态的文字放进轨道;小尺寸也显示。长文字自然撑开轨道,拇指仍停在轨道两端并保留移动动画。active、inactive 插槽可放图标、短文字,优先于对应的文字属性;不开 inlinePrompt 时插槽在两侧,开启后只挂载当前状态内容。空插槽沿 Vue 规则回退到文字。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiIcon, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const value = ref(false)
const inline = ref(true)
const sizes = ['large', 'default', 'small'] as const
</script>
<template>
<HuiSpace class="switch-inline-demo" direction="vertical" fill>
<HuiSpace wrap>
<div v-for="size in sizes" :key="size">
<span>{{ size }}:</span>
<HuiSwitch
v-model="value"
:size="size"
inline-prompt
active-text="启用"
inactive-text="停用"
aria-label="启用账号"
/>
</div>
</HuiSpace>
<HuiSwitch
inline-prompt
active-text="允许发布"
inactive-text="等待管理员审批的长文字"
aria-label="允许发布"
/>
<HuiSpace wrap>
<HuiSwitch
:model-value="true"
inline-prompt
loading
active-text="启用"
inactive-text="停用"
aria-label="加载中的启用状态"
/>
<HuiSwitch
:model-value="false"
inline-prompt
loading
active-text="启用"
inactive-text="停用"
aria-label="加载中的停用状态"
/>
<HuiSwitch
:model-value="true"
inline-prompt
disabled
active-text="启用"
aria-label="禁用操作"
/>
</HuiSpace>
<HuiButton class="inline-placement-toggle" @click="inline = !inline"
>切换插槽在轨道内或两侧</HuiButton
>
<HuiSwitch
v-model="value"
class="inline-slots"
:inline-prompt="inline"
active-text="文字回退"
inactive-text="文字回退"
aria-label="图标状态"
>
<template #active
><HuiSpace :size="4"
><HuiIcon name="check" size="xs" /><span>可用</span></HuiSpace
></template
>
<template #inactive
><HuiSpace :size="4"
><HuiIcon name="close" size="xs" /><span>暂停</span></HuiSpace
></template
>
</HuiSwitch>
<span class="inline-status">当前:{{ value }};插槽在轨道内:{{ inline }}</span>
</HuiSpace>
</template>
轨道提示带 aria-hidden="true",用于显示状态,不替代开关的固定名称。使用 aria-label 或表单标签命名;名称不随状态文字改变。加载期间保持原状态提示,圆钮继续显示加载图标;前置检查放行后更新,受控时以父级回传值为准。
自定义值
用 active-value 和 inactive-value 指定打开、关闭时的值,可以是字符串或数字。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const status = ref('on')
const flag = ref(0)
</script>
<template>
<HuiSpace wrap>
<HuiSwitch v-model="status" active-value="on" inactive-value="off" />
<HuiSwitch v-model="flag" :active-value="1" :inactive-value="0" />
</HuiSpace>
<p style="margin-top: 12px">status:'{{ status }}',flag:{{ flag }}</p>
</template>
事件
用户点击或按键切换,前置检查放行后依次触发 update:modelValue、change,参数是目标值。拒绝切换不触发这两个事件。在代码里改绑定值不触发 change。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const value = ref(false)
const logs = ref<string[]>([])
const onChange = (next: string | number | boolean) => {
logs.value = [`change:${next}`, ...logs.value].slice(0, 5)
}
</script>
<template>
<HuiSpace wrap>
<HuiSwitch v-model="value" @change="onChange" />
<HuiButton size="small" @click="value = !value">在代码里切换(不触发)</HuiButton>
</HuiSpace>
<p style="margin-top: 12px">最近的事件(新的在前):{{ logs.join(',') || '还没有' }}</p>
</template>
在表单里使用
放在 HuiFormItem 里时,值变化触发 change 规则,开关通过 aria-labelledby 关联表单项的标签,不会随原生 <form> 提交。false 不算空值,required 拦不住没打开的开关,要写 validator 判断。不需要校验时设 :validate-event="false"。
校验不通过时表单项下面显示错误信息,开关本身的颜色不变。点“提交”看看:
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiButton, HuiForm, HuiFormItem, HuiSwitch } from '@nscode/handy-ui'
import type { FormRule } from '@nscode/handy-ui'
const formRef = ref<InstanceType<typeof HuiForm>>()
const model = reactive({ agree: false })
const rules: Record<string, FormRule[]> = {
agree: [{ validator: (_rule, value) => value === true, message: '请先开启', trigger: 'change' }]
}
const submit = () => {
formRef.value?.validate()
}
</script>
<template>
<HuiForm ref="formRef" :model="model" :rules="rules" label-width="120px" @submit.prevent>
<HuiFormItem label="接收服务通知" prop="agree">
<HuiSwitch v-model="model.agree" />
</HuiFormItem>
<HuiFormItem>
<HuiButton type="primary" @click="submit">提交</HuiButton>
</HuiFormItem>
</HuiForm>
</template>
键盘操作
开关可以用 Tab 键聚焦,聚焦后按空格或回车切换。按住不放只切换一次。
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| modelValue | boolean | string | number | undefined | 绑定值,支持 v-model,等于 activeValue 时开启。未传时内部初值 false;传入属性(含 undefined)即受控。 |
| disabled | boolean | false | 是否禁用 |
| loading | boolean | false | 外部加载状态,与前置检查的等待状态取或。加载中不能切换,仍可聚焦 |
| beforeChange | (newValue: boolean | string | number) => boolean | void | Promise<boolean | void> | — | 切换前检查目标值;仅 false、抛错或 Promise 拒绝拦截。异步等待时自动加载且忽略重复操作 |
| size | 'large' | 'default' | 'small' | - | 尺寸:轨道 44×22 / 36×18 / 28×14 像素。不写时跟随 FormItem、Form、ConfigProvider,都没有时是 'default' |
| shape | 'round' | 'square' | 'round' | 形状:round 两端是半圆,square 是圆角长方形 |
| inlinePrompt | boolean | false | 当前状态文字或插槽显示在轨道内,三种尺寸均支持。 |
| activeText | string | '' | 打开时对应的文字,显示在开关右边 |
| inactiveText | string | '' | 关闭时对应的文字,显示在开关左边 |
| activeValue | boolean | string | number | true | 打开时的值 |
| inactiveValue | boolean | string | number | false | 关闭时的值 |
| validateEvent | boolean | true | 值变化时是否触发所在表单项的校验 |
Events
| 事件 | 回调参数 | 说明 |
|---|---|---|
| update:modelValue | (value: boolean | string | number) | 用户操作且前置检查放行后请求更新,v-model 用的就是它 |
| change | (value: boolean | string | number) | 紧随 update:modelValue,参数是目标值;父不回填时仍保持父值 |
Slots
| 插槽 | 说明 |
|---|---|
| active | 打开内容,优先于 activeText;默认在右侧,inlinePrompt 时在轨道内且只在打开时挂载 |
| inactive | 关闭内容,优先于 inactiveText;默认在左侧,inlinePrompt 时在轨道内且只在关闭时挂载 |
类型
import type { SwitchSize, SwitchShape, SwitchProps, SwitchSlots } from '@nscode/handy-ui'
type SwitchSize = 'large' | 'default' | 'small'
type SwitchShape = 'round' | 'square'
interface SwitchProps {
modelValue?: string | number | boolean
disabled?: boolean
loading?: boolean
beforeChange?: (newValue: string | number | boolean) => boolean | void | Promise<boolean | void>
size?: SwitchSize
shape?: SwitchShape
activeText?: string
inactiveText?: string
inlinePrompt?: boolean
activeValue?: string | number | boolean
inactiveValue?: string | number | boolean
/** 值变化时是否触发所在表单项的校验,默认 true */
validateEvent?: boolean
}
焦点方法与公开类型
组件ref使用SwitchExpose。focus()聚焦当前、已选或首个可用控件,不改值、不打开文件选择框;禁用或卸载后不聚焦,只读按控件原合同保留可聚焦性。blur()只让本组件所属文档内的活动元素失焦,不影响外部焦点。组控件的focus/blur只在整组进出时各触发一次,内部移动不重复;既有表单校验行为保持。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSwitch, HuiButton, HuiSpace } from '@nscode/handy-ui'
import type { SwitchExpose } from '@nscode/handy-ui'
const control = ref<SwitchExpose>()
const value = ref(false)
const event = ref('等待操作')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @mousedown.prevent @click="control?.focus()">focus()</HuiButton>
<HuiButton @mousedown.prevent @click="control?.blur()">blur()</HuiButton>
</HuiSpace>
<HuiSwitch ref="control" v-model="value" @focus="event = 'focus'" @blur="event = 'blur'" />
<span>{{ event }}</span>
</HuiSpace>
</template>
| 方法 | 签名 |
|---|---|
| focus | () => void |
| blur | () => void |
整组件焦点事件
| 事件 | 参数 | 行为 |
|---|---|---|
| focus | event: FocusEvent | 焦点从组外进入时一次 |
| blur | event: FocusEvent | 焦点离开整组时一次,内部移动不重复 |