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。