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 相同。父元件拒絕更新時,畫面仍維持實際父值。執行期間切換模式會發出開發診斷,不另設 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>
自訂值
用 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 並非空值;若要求必須開啟,應自行提供 validator,不能只用 required。設定 :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 鍵聚焦,聚焦後按空白或Enter切換。按住不放只切換一次。
軌道文字與狀態插槽
inlinePrompt 將目前狀態文字放入軌道,三種尺寸皆支援;長文字會撐開軌道,圓鈕仍停在兩端並保留動畫。active、inactive 插槽優先於對應文字屬性;未開啟時位於兩側,開啟後只掛載目前狀態的內容。空插槽沿 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 direction="vertical" fill>
<HuiSpace wrap>
<HuiSwitch
v-for="size in sizes"
:key="size"
v-model="value"
:size="size"
inline-prompt
active-text="啟用"
inactive-text="停用"
:aria-label="size + '帳號狀態'"
/>
</HuiSpace>
<HuiSwitch
inline-prompt
active-text="允許發布"
inactive-text="等待管理員核准的長文字"
aria-label="發布權限"
/>
<HuiSpace wrap>
<HuiSwitch
:model-value="true"
inline-prompt
loading
active-text="啟用"
aria-label="載入中的啟用狀態"
/>
<HuiSwitch
:model-value="false"
inline-prompt
loading
inactive-text="停用"
aria-label="載入中的停用狀態"
/>
<HuiSwitch
:model-value="true"
inline-prompt
disabled
active-text="啟用"
aria-label="禁用操作"
/>
</HuiSpace>
<HuiButton @click="inline = !inline">切換插槽位置</HuiButton>
<HuiSwitch
v-model="value"
: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>目前:{{ value }};插槽位於軌道內:{{ inline }}</span>
</HuiSpace>
</template>
軌道提示帶 aria-hidden="true",不取代開關固定名稱。以 aria-label 或表單標籤命名,名稱不隨狀態變更。載入期間保留原提示並顯示載入圖示;前置檢查放行後才請求更新,受控時仍以父元件回填值為準。
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 是圓角長方形 |
| activeText | string | '' | 開啟狀態文字;預設在右側,inlinePrompt時放在軌道內 |
| inactiveText | string | '' | 關閉狀態文字;預設在左側,inlinePrompt時放在軌道內 |
| activeValue | boolean | string | number | true | 打開時的值 |
| inactiveValue | boolean | string | number | false | 關閉時的值 |
| validateEvent | boolean | true | 值變化時是否觸發所在表單項的驗證 |
| inlinePrompt | boolean | false | 將目前狀態文字或插槽放在軌道內,三種尺寸皆支援,長文字會撐開軌道 |
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 } 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()。聚焦不更改狀態,也不會啟動切換前檢查;禁用或卸載後不執行。失焦只處理本元件所屬文件內的活動元素,不影響外部焦點。焦點進出元件時通知既有事件,內部移動不重複通知;表單驗證行為不變。
<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 | 焦點離開整組時一次,內部移動不重複 |