SelectInput 自訂選擇框
顯示單選文字或多選標籤,下拉面板可放入表格、樹、分頁或任意內容。選擇由面板處理,SelectInput 負責顯示結果、通知查詢及管理展開狀態。
引入
ts
import { HuiSelectInput } from '@nscode/handy-ui'
import type { SelectInputExpose, SelectInputTag } from '@nscode/handy-ui'
示例
自訂面板與單選文字
vue
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSelectInput, HuiSpace } from '@nscode/handy-ui'
const label = ref('')
const visible = ref(false)
const choose = (value: string) => {
label.value = value
visible.value = false
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSelectInput v-model:visible="visible" :label="label" placeholder="選擇團隊">
<template #panel="{ close }">
<HuiSpace style="padding: 12px">
<HuiButton @click="choose('设计')">設計</HuiButton>
<HuiButton @click="choose('研发')">研發</HuiButton>
<HuiButton @click="close">關閉面板</HuiButton>
</HuiSpace>
</template>
</HuiSelectInput>
<span>已選:{{ label || '(空)' }};展開:{{ visible }}</span>
</HuiSpace>
</template>
表格分頁、查詢與確認後移除
下面示例由頁面管理跨頁選擇。查詢只接受 inputChange;清除請求先等待確認,因此取消時選擇和查詢均保留。標籤移除、表格取消勾選和清除共用確認與過期保護。
vue
<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import {
HuiButton,
HuiCheckbox,
HuiMessageBox,
HuiPagination,
HuiSelectInput,
HuiSpace,
HuiTable
} from '@nscode/handy-ui'
import type { TableColumnConfig } from '@nscode/handy-ui'
const initialRows = [
{ id: 1, name: '林可', team: '设计' },
{ id: 2, name: '陈安', team: '研发' },
{ id: 3, name: '周宁', team: '产品' },
{ id: 4, name: '何青', team: '研发' },
{ id: 5, name: '苏禾', team: '运营' },
{ id: 6, name: '方远', team: '设计' },
{ id: 7, name: '陆川', team: '研发' },
{ id: 8, name: '沈悦', team: '产品' }
]
const rows = ref(initialRows.map((row) => ({ ...row })))
const selected = ref<(string | number)[]>([1, 3])
const visible = ref(false)
const query = ref('')
const page = ref(1)
const pending = ref(false)
const readonly = ref(false)
const collapsed = ref(true)
const status = ref('標籤與跨頁勾選由頁面管理;移除或清除前需要確認')
const pageSize = 4
const columns: TableColumnConfig[] = [
{ prop: 'name', label: '姓名', width: 130 },
{ prop: 'team', label: '團隊', width: 130 }
]
const filtered = computed(() =>
rows.value.filter((row) => `${row.name}${row.team}`.includes(query.value.trim()))
)
const pageRows = computed(() =>
filtered.value.slice((page.value - 1) * pageSize, page.value * pageSize)
)
const pageKeys = computed(() =>
selected.value.filter((key) => pageRows.value.some((row) => row.id === key))
)
const tags = computed(() =>
selected.value.flatMap((key) => {
const row = rows.value.find((item) => item.id === key)
return row ? [{ value: key, label: row.name }] : []
})
)
let alive = true
let revision = 0
watch([selected, rows, query, readonly], () => revision++, { deep: true, flush: 'sync' })
watch(query, () => {
page.value = 1
})
onBeforeUnmount(() => {
alive = false
revision++
})
const confirmSelection = async (
next: (string | number)[],
object: string,
clearQuery = false
) => {
if (!alive || pending.value || readonly.value) return
const snapshot = selected.value.slice()
const collection = rows.value
const request = revision
pending.value = true
status.value = `等待確認${object},目前選擇保持不變`
try {
const result = await HuiMessageBox.confirm(
`確定${object}?僅改變本次選擇,不刪除成員資料,其他已選成員保持不變。`,
'確認修改選擇',
{ confirmButtonText: '確認移除', confirmButtonType: 'danger' }
)
if (!alive) return
if (
request !== revision ||
readonly.value ||
rows.value !== collection ||
snapshot.length !== selected.value.length ||
snapshot.some((key, index) => key !== selected.value[index])
) {
status.value = '選擇、查詢或資料已變化,舊確認失效,請重新操作'
return
}
if (result.action !== 'confirm') {
status.value = '已取消,全部選擇保持不變'
return
}
selected.value = next.slice()
if (clearQuery) query.value = ''
status.value = `已${object}`
} catch {
if (alive && request === revision) status.value = '已取消或關閉確認,全部選擇和查詢保持不變'
} finally {
if (alive) pending.value = false
}
}
const removeTag = (key: string | number) => {
const tag = tags.value.find((item) => item.value === key)
if (tag)
void confirmSelection(
selected.value.filter((value) => value !== key),
`移除成員「${tag.label}」`
)
}
const clear = () => {
if (!selected.value.length) {
query.value = ''
return
}
void confirmSelection([], `清除全部 ${selected.value.length} 位已選成員`, true)
}
const updatePage = (keys: (string | number)[]) => {
if (pending.value || readonly.value) return
const pageIds = new Set(pageRows.value.map((row) => row.id))
const next = [...selected.value.filter((key) => !pageIds.has(key as number)), ...keys]
const removed = selected.value.filter((key) => !next.includes(key))
if (removed.length) {
const names = tags.value
.filter((tag) => removed.includes(tag.value))
.map((tag) => tag.label)
.join('、')
void confirmSelection(next, `移除本頁 ${removed.length} 位成員「${names}」`)
} else selected.value = next
}
// 查詢只接受inputChange;clear發出的文字更新請求等確認後再接受。
const inputChange = (value: string) => {
if (!pending.value && !readonly.value) query.value = value
}
const refresh = () => {
revision++
rows.value = rows.value.map((row) => ({ ...row }))
status.value = '已模擬資料刷新;待處理的舊確認已失效,選擇保持不變'
}
const toggleReadonly = () => {
readonly.value = !readonly.value
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiCheckbox v-model="collapsed">折疊標籤</HuiCheckbox>
<HuiButton class="select-input-demo-refresh" size="small" @click="refresh"
>模擬資料刷新</HuiButton
>
<HuiButton class="select-input-demo-readonly" size="small" @click="toggleReadonly">{{
readonly ? '恢復選擇' : '切到唯讀'
}}</HuiButton>
</HuiSpace>
<HuiSelectInput
v-model:visible="visible"
:input-value="query"
:tags="tags"
:collapse-tags="collapsed"
:max-collapse-tags="2"
:disabled="pending || readonly"
:loading="pending"
:popup-width="420"
multiple
filterable
clearable
placeholder="依姓名或團隊搜尋成員"
aria-label="選擇成員"
@input-change="inputChange"
@remove-tag="removeTag"
@clear="clear"
>
<template #panel>
<HuiSpace direction="vertical" fill style="padding: 12px">
<HuiTable
:data="pageRows"
:columns="columns"
:selected-keys="pageKeys"
:row-selectable="() => !pending && !readonly"
row-key="id"
selectable
@update:selected-keys="updatePage"
/>
<HuiPagination
v-model:current-page="page"
:total="filtered.length"
:page-size="pageSize"
:disabled="pending"
layout="prev,pager,next"
/>
</HuiSpace>
</template>
</HuiSelectInput>
<span class="select-input-demo-status" role="status">{{ status }}</span>
<span class="select-input-demo-selected"
>已選:{{ tags.map((tag) => tag.label).join('、') || '(空)' }}</span
>
<span
>等待確認期間禁止重複移除;取消、關閉或 Esc
保留選擇和查詢。資料刷新、切唯讀或卸載會使舊確認失效。</span
>
</HuiSpace>
</template>
樹面板
vue
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelectInput, HuiSpace, HuiTree } from '@nscode/handy-ui'
import type { TreeNodeData } from '@nscode/handy-ui'
const visible = ref(false)
const label = ref('')
const selected = ref<string | number | null>(null)
const nodes: TreeNodeData[] = [
{
id: 'design',
label: '設計',
children: [
{ id: 'visual', label: '視覺設計' },
{ id: 'interaction', label: '互動設計' }
]
},
{ id: 'engineering', label: '研發' }
]
// node-click 的參數是 { node, key }
const choose = ({ node, key }: { node: TreeNodeData; key: string | number }) => {
selected.value = key
label.value = node.label ?? ''
visible.value = false
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSelectInput v-model:visible="visible" :label="label" placeholder="選擇團隊">
<template #panel
><HuiTree
:data="nodes"
:current-key="selected"
default-expand-all
highlight-current
@node-click="choose"
/></template>
</HuiSelectInput>
<span>節點:{{ selected ?? '(空)' }}</span>
</HuiSpace>
</template>
尺寸、寬度、位置與點擊策略
trigger 表示面板寬度至少等於觸發框,auto 依內容決定,數字以 px 計。面板始終受可視區域寬度限制。keepOpenOnPanelClick=false 時,面板內的正常點擊會請求關閉;若事件已 preventDefault(),或回呼已重新開啟面板,則保留新會話。
vue
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCheckbox, HuiSelect, HuiSelectInput, HuiSpace } from '@nscode/handy-ui'
import type { PopperPlacement } from '@nscode/handy-ui'
const sizes = ['large', 'default', 'small'] as const
const widths = ['trigger', 'auto', 420] as const
const positions: PopperPlacement[] = [
'top',
'top-start',
'top-end',
'bottom',
'bottom-start',
'bottom-end',
'left',
'left-start',
'left-end',
'right',
'right-start',
'right-end'
]
const placement = ref<PopperPlacement>('bottom-start')
const keep = ref(true)
const loading = ref(false)
const disabled = ref(false)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap
><HuiCheckbox v-model="keep">點擊面板保持打開</HuiCheckbox
><HuiCheckbox v-model="loading">loading</HuiCheckbox
><HuiCheckbox v-model="disabled">disabled</HuiCheckbox></HuiSpace
>
<HuiSelect v-model="placement" :options="positions.map((value) => ({ label: value, value }))" />
<HuiSelectInput
v-for="(size, index) in sizes"
:key="size"
:size="size"
:popup-width="widths[index]"
:placement="placement"
:keep-open-on-panel-click="keep"
:loading="loading"
:disabled="disabled"
:placeholder="`${size} / ${widths[index]}`"
>
<template #panel="{ close }"
><HuiSpace style="padding: 12px"
><span>{{ size }} / {{ widths[index] }}</span
><HuiButton @click="close">關閉</HuiButton></HuiSpace
></template
>
</HuiSelectInput>
</HuiSpace>
</template>
標籤、前綴、清除與空態插槽
標籤由頁面保存:元件只發 removeTag、clear 請求,頁面收到後自己改 tags,元件不會改。tag.close() 與預設標籤移除入口相同;closable=false 不允許發出該項移除請求,清除時頁面也保留它。要先確認再改,照「表格分頁、查詢與確認後移除」範例。
vue
<script setup lang="ts">
import { ref } from 'vue'
import {
HuiButton,
HuiCheckbox,
HuiIcon,
HuiSelect,
HuiSelectInput,
HuiSpace
} from '@nscode/handy-ui'
import type { SelectInputTag } from '@nscode/handy-ui'
const initialTags: SelectInputTag[] = [
{ value: 1, label: '數字1' },
{ value: '1', label: '文字1' },
{ value: 2, label: '固定項', closable: false },
{ value: 3, label: '第三項' }
]
const tags = ref(initialTags.slice())
const types = ['primary', 'success', 'warning', 'danger', 'info', 'help'] as const
const tagType = ref<(typeof types)[number]>('primary')
const collapse = ref(true)
const event = ref('等待請求')
// 1 和 '1' 是兩個不同的標籤,按嚴格相等刪除
const remove = (value: string | number, source: string) => {
tags.value = tags.value.filter((tag) => tag.value !== value)
event.value = `${source}請求移除 ${typeof value} ${value},頁面已刪除`
}
// 清除時保留不可移除的固定項
const clearTags = () => {
tags.value = tags.value.filter((tag) => tag.closable === false)
event.value = 'clear:頁面已清除,固定項保留'
}
const reset = () => {
tags.value = initialTags.slice()
event.value = '已恢復全部標籤'
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap
><HuiCheckbox v-model="collapse">collapseTags</HuiCheckbox
><HuiSelect
v-model="tagType"
:options="types.map((value) => ({ label: value, value }))"
/><HuiButton @click="reset">恢復標籤</HuiButton></HuiSpace
>
<HuiSelectInput
:tags="tags"
:tag-type="tagType"
:collapse-tags="collapse"
:max-collapse-tags="2"
multiple
clearable
@remove-tag="(value) => remove(value, '預設標籤')"
@clear="clearTags"
>
<template #prefix><HuiIcon name="search" /></template>
<template #empty>請透過 panel 插槽設定內容</template>
</HuiSelectInput>
<HuiSelectInput
:tags="tags"
multiple
:collapse-tags="false"
@remove-tag="(value) => remove(value, '自訂標籤')"
>
<template #tag="{ tag, close }"
><HuiButton size="small" :disabled="tag.closable === false" @click.stop="close($event)">{{
tag.label
}}</HuiButton></template
>
</HuiSelectInput>
<span role="status">{{ event }}</span>
</HuiSpace>
</template>
輸入受控、正規化與父拒絕
inputValue 和 visible 分別受控。傳入屬性但不回填就保留父值;顯式 undefined 同樣受控。沒有屬性時內部保存查詢和展開狀態。範例預設接受輸入並轉成大寫;取消勾選後父元件不回填,輸入框保持父值。
vue
<script setup lang="ts">
import { ref } from 'vue'
import { HuiCheckbox, HuiSelectInput, HuiSpace } from '@nscode/handy-ui'
const query = ref('ABC')
const accept = ref(true)
const event = ref('等待輸入')
const update = (value: string) => {
if (accept.value) query.value = value.toUpperCase()
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiCheckbox v-model="accept">接受輸入並轉成大寫;關閉時父元件拒絕輸入</HuiCheckbox>
<HuiSelectInput
:input-value="query"
filterable
@update:input-value="update"
@input-change="event = $event"
><template #panel
><span>按業務查詢:{{ query }}</span></template
></HuiSelectInput
>
<span>父值:{{ query }};最新請求:{{ event }}</span>
</HuiSpace>
</template>
表單、輸入組與公開方法
vue
<script setup lang="ts">
import { reactive, ref } from 'vue'
import {
HuiButton,
HuiCheckbox,
HuiForm,
HuiFormItem,
HuiInputGroup,
HuiSelectInput,
HuiSpace
} from '@nscode/handy-ui'
import type { SelectInputExpose } from '@nscode/handy-ui'
const model = reactive({ team: '' })
const control = ref<SelectInputExpose>()
const readonly = ref(false)
const validateEvent = ref(true)
const event = ref('等待操作')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap
><HuiCheckbox v-model="readonly">表單唯讀</HuiCheckbox
><HuiCheckbox v-model="validateEvent">validateEvent</HuiCheckbox></HuiSpace
>
<HuiForm :model="model" :readonly="readonly" size="small">
<HuiFormItem
label="團隊"
prop="team"
tip="面板選擇由頁面管理"
:rules="[{ required: true, message: '請選擇團隊', trigger: 'blur' }]"
>
<HuiInputGroup>
<HuiSelectInput
ref="control"
:label="model.team"
:validate-event="validateEvent"
@focus="event = 'focus'"
@blur="event = 'blur'"
@clear="event = 'clear請求'"
>
<template #panel="{ close }"
><HuiButton
@click="
() => {
model.team = '设计'
close()
}
"
>選擇設計團隊</HuiButton
></template
>
</HuiSelectInput>
<HuiButton @click="control?.open()">open()</HuiButton>
</HuiInputGroup>
</HuiFormItem>
</HuiForm>
<HuiSpace wrap
><HuiButton @click="control?.close()">close()</HuiButton
><HuiButton @click="control?.focus()">focus()</HuiButton
><HuiButton @click="control?.blur()">blur()</HuiButton
><HuiButton @click="control?.clear()">clear():僅發請求</HuiButton></HuiSpace
>
<span role="status">{{ event }}</span>
</HuiSpace>
</template>
Props
| 屬性 | 類型 | 預設值 | 說明 |
|---|---|---|---|
| label | string | — | 單選展示文字;不表示選擇值 |
| tags | SelectInputTag[] | [] | 多選展示標籤;不由元件修改 |
| multiple | boolean | false | 多選標籤展示 |
| visible | boolean | 未傳時內部 false | 屬性存在即受控,支援 v-model:visible |
| inputValue | string | 未傳時內部 '' | 查詢文字,支援 v-model:input-value |
| filterable | boolean | false | 顯示輸入框;不執行篩選或請求 |
| placeholder | string | 語言包“請選擇” | 顯式空字串有效 |
| clearable | boolean | false | 顯示清除請求入口 |
| disabled | boolean | false | 禁止互動;同時繼承輸入組及表單禁用 |
| loading | boolean | false | 觸發框等待圖示及 aria-busy,不替換面板內容 |
| size | 'large' | 'default' | 'small' | 繼承 | 顯式 > InputGroup > FormItem > Form > defaults > 全域尺寸 |
| collapseTags | boolean | true | 折疊超出數量的標籤 |
| maxCollapseTags | number | 3 | 展示標籤數量;0 時僅顯示 +N |
| tagType | TagType | 'primary' | primary/success/warning/danger/info/help |
| popupWidth | 'trigger' | 'auto' | number | 'trigger' | 最小觸發框寬度、內容寬度、固定 px |
| placement | PopperPlacement | 'bottom-start' | 12 種方向,空間不足時自動翻轉 |
| keepOpenOnPanelClick | boolean | true | 點擊面板是否保持打開 |
| validateEvent | boolean | true | 展示值變化及整組關閉失焦時自動驗證 |
Events
| 事件 | 參數 | 說明 |
|---|---|---|
| update:visible | visible: boolean | 請求展開/收起;兩種模式均通知 |
| update:inputValue | value: string | 查詢更新請求 |
| inputChange | value: string | 組字完成後的查詢;先 update 再通知 |
| removeTag | value: string | number | 請求移除標籤;不修改外部值 |
| clear | — | 先 update:inputValue('') 再 clear;不發選擇 change |
| focus | event: FocusEvent | 焦點進入整個控制項一次 |
| blur | event: FocusEvent | 焦點離開觸發框、面板及所屬子浮層一次 |
模板監聽使用 @input-change、@remove-tag、@update:input-value;事件類型聲明使用駝峰。
Slots
| 插槽 | 參數 | 說明 |
|---|---|---|
| panel | { close: () => void } | 任意面板;內容可正常聚焦和點擊 |
| prefix | — | 觸發框前綴 |
| tag | { tag: SelectInputTag, close: (event?: Event) => void } | 自訂單個標籤;close 發移除請求 |
| empty | — | 沒有 panel 插槽時的空態 |
方法
透過 ref<SelectInputExpose>() 呼叫:
| 方法 | 說明 |
|---|---|
| open() | 請求打開;程式呼叫保持現有焦點 |
| close() | 請求關閉;父拒絕時仍保持打開 |
| focus() | 聚焦查詢輸入框或非輸入觸發框;禁用/卸載時無操作 |
| blur() | 僅使本控制項分支內的活動元素失焦 |
| clear() | 與清除入口相同;不修改外部 label/tags,不搶外部焦點 |
類型
ts
interface SelectInputTag {
label: string
value: string | number
closable?: boolean
}
interface SelectInputExpose {
open: () => void
close: () => void
focus: () => void
blur: () => void
clear: () => void
}
另導出 SelectInputProps、SelectInputEmits、SelectInputSlots、SelectInputPanelSlotProps、SelectInputTagSlotProps。