Select
Chooses one or more items from a dropdown. Use it when too many options make radio buttons or checkboxes impractical to display inline.
Import
import { HuiSelect, HuiSelectOption } from '@nscode/handy-ui'
Basic Usage
Pass options and bind the selected value with v-model. Null means no selection; an undefined parent value is also accepted as empty. Empty selectors display the placeholder, which defaults to the localized selection prompt.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type { SelectOption } from '@nscode/handy-ui'
const value = ref<string | null>(null)
const city = ref<string | null>(null)
const options: SelectOption[] = [
{ label: 'Beijing', value: 'beijing' },
{ label: 'Shanghai', value: 'shanghai' },
{ label: 'Guangzhou', value: 'guangzhou' }
]
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<HuiSelect v-model="value" :options="options" style="width: 240px" />
<HuiSelect
v-model="city"
:options="options"
placeholder="Choose your city"
style="width: 240px"
/>
</HuiSpace>
<span>Selected value: {{ value === null ? 'null' : (value ?? 'undefined') }}</span>
</HuiSpace>
</template>
Slot Options
Without options, place HuiSelectOption components in the default slot. Choose one approach rather than supplying both.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSelectOption } from '@nscode/handy-ui'
const value = ref<number>(2)
</script>
<template>
<HuiSelect v-model="value" style="width: 240px">
<HuiSelectOption label="Option 1" :value="1" />
<HuiSelectOption label="Option 2" :value="2" />
<HuiSelectOption label="Option 3" :value="3" />
</HuiSelect>
</template>
Custom Option Content
HuiSelectOption's default slot customizes option rendering. After selection, the trigger still displays its label.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSelectOption } from '@nscode/handy-ui'
const value = ref<string | null>(null)
const cities = [
{ label: 'Beijing', value: 'beijing', code: '010' },
{ label: 'Shanghai', value: 'shanghai', code: '021' },
{ label: 'Guangzhou', value: 'guangzhou', code: '020' }
]
</script>
<template>
<HuiSelect v-model="value" style="width: 240px">
<HuiSelectOption
v-for="city in cities"
:key="city.value"
:label="city.label"
:value="city.value"
>
<span>{{ city.label }}</span>
<span style="margin-left: 8px; font-size: 12px">Area code {{ city.code }}</span>
</HuiSelectOption>
</HuiSelect>
</template>
Field Mapping and Original Records
props maps value, label, disabled, and children to field names or getter functions. Their default fields are value, label, disabled, and options. Pass API records directly through options; getters receive the original record and should not mutate it.
Values must be strings or finite numbers. Numeric 0, string '0', and '' are distinct. An explicit empty label stays empty; only a missing label falls back to the value. The second change argument keeps extra fields and the original source-object reference.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type { SelectFieldNames, SelectSelected, SelectValue } from '@nscode/handy-ui'
interface Department {
code: string | number
name: string
team: string
locked?: boolean
}
const options: Department[] = [
{ code: 0, name: 'Numeric zero', team: 'Product' },
{ code: '0', name: 'String zero', team: 'Engineering' },
{ code: '', name: '', team: 'Empty label' },
{ code: 'off', name: 'Unavailable department', team: 'Operations', locked: true }
]
const fields: SelectFieldNames = { value: 'code', label: 'name', disabled: 'locked' }
const functions: SelectFieldNames = {
value: (row) => row.code,
label: (row) => `${String(row.name)} / ${String(row.team)}`,
disabled: (row) => row.locked === true
}
const value = ref<string | number | null>(0)
const other = ref<string | number | null>('0')
const multiple = ref<(string | number)[]>([0])
const output = ref('No selection change')
const changed = (next: SelectValue, selected: SelectSelected) => {
const originals = Array.isArray(selected) ? selected : selected ? [selected] : []
output.value = JSON.stringify({
value: next,
type: typeof next,
selected,
original:
originals.length > 0 &&
originals.every((original) => options.some((row) => (row as object) === original))
})
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiSelect
v-model="value"
:options="options"
:props="fields"
style="width: 240px"
@change="changed"
/>
<HuiSelect
v-model="other"
:options="options"
:props="functions"
style="width: 280px"
@change="changed"
/>
<HuiSelect
v-model="multiple"
:options="options"
:props="fields"
multiple
style="width: 300px"
@change="changed"
/>
</HuiSpace>
<span role="status">{{ output }}</span>
<span>Multiple model: {{ JSON.stringify(multiple) }}</span>
</HuiSpace>
</template>
Explicit Empty Sources and Slot Priority
The first selector omits options and uses its default slot. The other three explicitly supply an empty source and display an empty state. An explicitly supplied data source takes precedence over default-slot options, even for [], undefined, or null; supplying both sources also emits a development diagnostic. An empty array returned by remoteMethod is a valid empty source.
<script setup lang="ts">
import { HuiSelect, HuiSelectOption, HuiSpace } from '@nscode/handy-ui'
</script>
<template>
<HuiSpace wrap>
<HuiSelect placeholder="options omitted" style="width: 200px">
<HuiSelectOption value="slot" label="Slot option" />
</HuiSelect>
<HuiSelect :options="[]" placeholder="Explicit []" style="width: 200px" />
<HuiSelect :options="undefined" placeholder="Explicit undefined" style="width: 200px" />
<HuiSelect :options="null" placeholder="Explicit null" style="width: 200px" />
</HuiSpace>
</template>
Option Groups
A record with a valid value is always a leaf, even when it also has an options or children business field. Records without a value are groups only when the mapped children field is an array. That field defaults to options; customize it with props.children. Empty groups and groups with no matching leaves are hidden. Search matches leaf display labels rather than group headings.
For slot options, use HuiSelectOptionGroup with label, disabled, and the default slot. Groups may nest. An ancestor's disabled state cannot be overridden by false on a descendant. Headings are neither selectable nor keyboard-navigation targets; disabled selected leaves retain their selected appearance.
<script setup lang="ts">
import { computed, ref } from 'vue'
import {
HuiButton,
HuiSelect,
HuiSelectOption,
HuiSelectOptionGroup,
HuiSpace
} from '@nscode/handy-ui'
const value = ref<string | number | null>(null)
const slotValue = ref<string | number | null>(null)
const disabled = ref(false)
const groups = computed(() => [
{
label: 'Engineering',
disabled: disabled.value,
options: [
{ value: 'a', label: 'Alex' },
{ value: 'b', label: 'Blair' }
]
},
{
label: 'Unavailable group',
disabled: true,
options: [{ value: 'old', label: 'Former member' }]
},
{ label: 'Empty group', options: [] }
])
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="disabled = !disabled">Engineering disabled: {{ disabled }}</HuiButton>
<HuiSpace wrap>
<HuiSelect
v-model="value"
:options="groups"
filterable
placeholder="Data groups"
style="width: 240px"
/>
<HuiSelect v-model="slotValue" filterable placeholder="Slot groups" style="width: 240px">
<HuiSelectOptionGroup label="Engineering" :disabled="disabled">
<HuiSelectOptionGroup label="Subgroup" :disabled="false">
<HuiSelectOption value="slot-a" label="Alex" />
<HuiSelectOption value="slot-b" label="Blair" />
</HuiSelectOptionGroup>
</HuiSelectOptionGroup>
<HuiSelectOptionGroup label="Unavailable group" disabled>
<HuiSelectOption value="old" label="Former member" />
</HuiSelectOptionGroup>
<HuiSelectOptionGroup label="Empty group" />
</HuiSelect>
</HuiSpace>
<span>Data selection: {{ value ?? 'Empty' }}; slot selection: {{ slotValue ?? 'Empty' }}</span>
</HuiSpace>
</template>
Groups use role="group" and a separate heading ID for their accessible names. Slot wrappers may register children after mounting, so SSR and the first client render retain group containers; empty groups are hidden after actual registration. The dropdown itself starts hidden. Group context belongs only to the nearest matching selector: an independent selector inside option content does not inherit the outer group's disabled state or registration.
Fixed Header, Footer and Data Option Content
header and footer remain outside the option scroll area, including during loading or with empty data. The order is header, selection toolbar, creation row and options, then footer. Each panel slot receives only close(), which closes this dropdown. Native inputs, buttons and owned child popups keep their interaction and are not treated as option selection or type-ahead input.
The option slot replaces only the body of data-source leaves. It receives the original option, selected, disabled, and index. Indexes start at zero among filtered logical leaves and exclude group headings. The selector keeps its role, ARIA, click behavior and check mark; virtual rows use the same scope. Manually written HuiSelectOption children retain their own default-slot content.
<script setup lang="ts">
import { computed, ref } from 'vue'
import { HuiButton, HuiModal, HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type { SelectSelected, SelectValue } from '@nscode/handy-ui'
const query = ref('')
const value = ref<SelectValue>('a')
const modalVisible = ref(false)
const status = ref('No selection change')
const members = [
{ value: 'a', label: 'Alex', businessCode: 'RD-001' },
{ value: 'b', label: 'Blair', businessCode: 'RD-002' },
{ value: 'off', label: 'Unavailable member', businessCode: 'RD-003', disabled: true }
]
const groups = computed(() => [
{
label: 'Engineering',
options: members.filter((member) =>
member.label.toLowerCase().includes(query.value.toLowerCase())
)
}
])
const changed = (next: SelectValue, selected: SelectSelected) => {
status.value = JSON.stringify({ value: next, selected })
}
const openHelp = (close: () => void) => {
close()
modalVisible.value = true
status.value = 'Dropdown closed; information dialog opened'
}
</script>
<template>
<HuiSpace class="select-panel-demo" direction="vertical" fill>
<HuiButton>Previous page button</HuiButton>
<HuiSelect
v-model="value"
:options="groups"
style="width: 360px; max-width: 100%"
@change="changed"
>
<template #header="{ close }">
<HuiSpace direction="vertical" fill>
<label class="select-panel-search-label">
Search members
<input
v-model="query"
class="select-panel-search"
aria-label="Filter engineering members"
/>
</label>
<HuiButton size="small" @click="close">Close list</HuiButton>
</HuiSpace>
</template>
<template #option="{ option, selected, disabled, index }">
<HuiSpace class="select-panel-option" :data-index="index" direction="vertical" :size="2">
<span>{{ index + 1 }}. {{ option.label }}</span>
<small
>{{ option.businessCode }} ·
{{ disabled ? 'Disabled' : selected ? 'Selected' : 'Available' }}</small
>
</HuiSpace>
</template>
<template #footer="{ close }">
<HuiSpace wrap>
<HuiButton size="small" @click="openHelp(close)">Option information</HuiButton>
<HuiButton size="small" @click="close">Close list</HuiButton>
</HuiSpace>
</template>
</HuiSelect>
<HuiButton>Next page button</HuiButton>
<span role="status">{{ status }}</span>
<HuiSelect :options="[]" empty-text="No members" style="width: 360px; max-width: 100%">
<template #header><strong>Scope: all members</strong></template>
<template #footer="{ close }">
<HuiButton size="small" @click="close">Skip selection</HuiButton>
</template>
</HuiSelect>
<HuiModal v-model:visible="modalVisible" title="Option information" :width="440">
<p>Opening this dialog does not create or remove business data.</p>
<template #footer>
<HuiButton @click="modalVisible = false">Understood</HuiButton>
</template>
</HuiModal>
</HuiSpace>
</template>
<style scoped>
.select-panel-search-label {
display: flex;
align-items: center;
gap: var(--hui-spacing-2);
color: var(--hui-text-color);
}
.select-panel-search {
width: 100%;
min-width: 0;
padding: var(--hui-spacing-1) var(--hui-spacing-2);
font: inherit;
color: var(--hui-text-color);
background: var(--hui-bg-color);
border: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color);
border-radius: var(--hui-border-radius);
}
.select-panel-option small {
color: var(--hui-text-color-secondary);
}
</style>
Available header controls and selection-toolbar controls form the leading focus segment, followed by the trigger and footer. Shift+Tab from the trigger enters the last leading control; Tab from that control returns to the trigger. Tab from the trigger enters the first footer control, and Shift+Tab returns. Leaving either outer boundary closes the list and continues page focus order. Calling a slot's close() does not take focus back from a newly opened dialog.
Disabled
Disabled prevents opening the selector, hides its clear button and removes tag close icons in multiple mode. Disabled on an individual option prevents choosing it through mouse or keyboard. An already selected disabled option can still be removed through its tag close icon in multiple mode.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type { SelectOption } from '@nscode/handy-ui'
const empty = ref<string | null>(null)
const single = ref<string>('beijing')
const multi = ref<string[]>(['beijing', 'shanghai'])
const value = ref<string | null>(null)
const values = ref<string[]>(['shanghai'])
const options: SelectOption[] = [
{ label: 'Beijing', value: 'beijing' },
{ label: 'Shanghai (disabled)', value: 'shanghai', disabled: true },
{ label: 'Guangzhou', value: 'guangzhou' }
]
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">Entire selector disabled</span>
<HuiSelect v-model="empty" :options="options" disabled style="width: 200px" />
<HuiSelect v-model="single" :options="options" disabled clearable style="width: 200px" />
<HuiSelect v-model="multi" :options="options" multiple disabled style="width: 260px" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">Disabled options</span>
<HuiSelect v-model="value" :options="options" style="width: 200px" />
<HuiSelect v-model="values" :options="options" multiple style="width: 260px" />
</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>
Clearable
Clearable shows a clear button when nonempty, hidden while empty or disabled. Clearing requests null in single mode or [] in multiple mode.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
const value = ref<string | null | undefined>('shanghai')
const values = ref<string[]>(['beijing', 'shanghai'])
const options = [
{ label: 'Beijing', value: 'beijing' },
{ label: 'Shanghai', value: 'shanghai' },
{ label: 'Guangzhou', value: 'guangzhou' }
]
</script>
<template>
<HuiSpace wrap>
<HuiSelect v-model="value" clearable :options="options" style="width: 240px" />
<HuiSelect v-model="values" multiple clearable :options="options" style="width: 300px" />
</HuiSpace>
<p style="margin-top: 12px">
Single: {{ value === null ? 'null' : (value ?? 'undefined') }}; multiple:
{{ JSON.stringify(values) }}
</p>
</template>
Internal and Controlled Values
Without modelValue, single mode stores null and multiple mode stores an empty array internally. Listening only for updates does not make it controlled. A supplied prop uses the parent's actual value; explicit undefined means controlled and empty. Parent acceptance or normalization updates the display. Rejection preserves text, tags, option highlighting and form values.
Removing the model prop restores earlier internal state. Switching control modes produces a development diagnostic; adding or removing listeners does not switch modes. Compare the five binding styles for single and multiple selection below. Select B, then click Parent redraw to inspect persistence. Clearing requests null or []; controlled usage requires parent acceptance.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type { SelectProps } from '@nscode/handy-ui'
const stateOptions = [
{ label: 'A', value: 'a' },
{ label: 'B', value: 'b' },
{ label: 'C', value: 'c' }
]
const stateSingle = ref<SelectProps['modelValue']>('a')
const stateMultiple = ref<SelectProps['modelValue']>(['a'])
const stateRedraw = ref(0)
const stateSingleLast = ref('None yet')
const stateMultipleLast = ref('None yet')
const recordSingle = (value: SelectProps['modelValue']) => {
stateSingleLast.value = JSON.stringify(value) ?? 'undefined'
}
const recordMultiple = (value: SelectProps['modelValue']) => {
stateMultipleLast.value = JSON.stringify(value) ?? 'undefined'
}
</script>
<template>
<HuiSpace class="select-q1-demo" direction="vertical" fill :data-parent="stateRedraw">
<HuiSpace wrap>
<HuiButton class="select-redraw" @click="stateRedraw++"
>Parent redraw {{ stateRedraw }}</HuiButton
>
<span>Select B, then redraw the parent to compare actual selection.</span>
</HuiSpace>
<HuiSpace align="start" wrap>
<HuiSpace class="select-single" direction="vertical" style="width: 360px; max-width: 100%">
<strong>Single selection</strong>
<HuiSpace class="select-local" wrap>
<span>Model prop omitted</span>
<HuiSelect filterable clearable :options="stateOptions" style="width: 200px" />
</HuiSpace>
<HuiSpace class="select-listener" wrap>
<span>Update listener only</span>
<HuiSelect
filterable
clearable
:options="stateOptions"
style="width: 200px"
@update:model-value="recordSingle"
/>
</HuiSpace>
<HuiSpace class="select-empty" wrap>
<span>Explicit undefined</span>
<HuiSelect
filterable
clearable
:options="stateOptions"
style="width: 200px"
:model-value="undefined"
/>
</HuiSpace>
<HuiSpace class="select-fixed" wrap>
<span>Fixed A; parent rejects updates</span>
<HuiSelect
filterable
clearable
:options="stateOptions"
style="width: 200px"
model-value="a"
/>
</HuiSpace>
<HuiSpace class="select-bound" wrap>
<span>Two-way binding</span>
<HuiSelect
filterable
clearable
:options="stateOptions"
style="width: 200px"
v-model="stateSingle"
/>
</HuiSpace>
<span class="select-status"
>Observed request: {{ stateSingleLast }}; bound value:
{{ JSON.stringify(stateSingle) ?? 'undefined' }}</span
>
</HuiSpace>
<HuiSpace class="select-multiple" direction="vertical" style="width: 360px; max-width: 100%">
<strong>Multiple selection</strong>
<HuiSpace class="select-local" wrap>
<span>Model prop omitted</span>
<HuiSelect multiple filterable clearable :options="stateOptions" style="width: 200px" />
</HuiSpace>
<HuiSpace class="select-listener" wrap>
<span>Update listener only</span>
<HuiSelect
multiple
filterable
clearable
:options="stateOptions"
style="width: 200px"
@update:model-value="recordMultiple"
/>
</HuiSpace>
<HuiSpace class="select-empty" wrap>
<span>Explicit undefined</span>
<HuiSelect
multiple
filterable
clearable
:options="stateOptions"
style="width: 200px"
:model-value="undefined"
/>
</HuiSpace>
<HuiSpace class="select-fixed" wrap>
<span>Fixed A; parent rejects updates</span>
<HuiSelect
multiple
filterable
clearable
:options="stateOptions"
style="width: 200px"
:model-value="['a']"
/>
</HuiSpace>
<HuiSpace class="select-bound" wrap>
<span>Two-way binding</span>
<HuiSelect
multiple
filterable
clearable
:options="stateOptions"
style="width: 200px"
v-model="stateMultiple"
/>
</HuiSpace>
<span class="select-status"
>Observed request: {{ stateMultipleLast }}; bound value:
{{ JSON.stringify(stateMultiple) ?? 'undefined' }}</span
>
</HuiSpace>
</HuiSpace>
</HuiSpace>
</template>
Multiple Selection
Multiple binds an array and displays selected options as tags. Selecting does not close the dropdown. A tag's close icon removes that selection.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect } from '@nscode/handy-ui'
const value = ref<string[]>(['beijing', 'shanghai'])
const options = [
{ label: 'Beijing', value: 'beijing' },
{ label: 'Shanghai', value: 'shanghai' },
{ label: 'Guangzhou', value: 'guangzhou' },
{ label: 'Shenzhen', value: 'shenzhen' }
]
</script>
<template>
<HuiSelect v-model="value" multiple clearable :options="options" style="width: 360px" />
</template>
Collapsed Tags
Multiple mode displays up to 3 tags by default and collapses the remainder into +N. Max-collapse-tags changes the visible count. Collapse-tags=false disables collapsing and shows every tag, wrapping when necessary.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
const value = ref<string[]>(['beijing', 'shanghai', 'guangzhou', 'shenzhen', 'hangzhou'])
const options = [
{ label: 'Beijing', value: 'beijing' },
{ label: 'Shanghai', value: 'shanghai' },
{ label: 'Guangzhou', value: 'guangzhou' },
{ label: 'Shenzhen', value: 'shenzhen' },
{ label: 'Hangzhou', value: 'hangzhou' },
{ label: 'Chengdu', value: 'chengdu' }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSelect v-model="value" multiple :options="options" />
<HuiSelect v-model="value" multiple :max-collapse-tags="1" :options="options" />
<HuiSelect v-model="value" multiple :collapse-tags="false" :options="options" />
</HuiSpace>
</template>
Tag-type accepts the same six types as HuiTag: primary (default), success, warning, danger, info and help. The collapsed +N tag uses the same type.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
const value = ref<string[]>(['beijing', 'shanghai', 'guangzhou', 'shenzhen'])
const types = ['primary', 'success', 'warning', 'danger', 'info', 'help'] as const
const options = [
{ label: 'Beijing', value: 'beijing' },
{ label: 'Shanghai', value: 'shanghai' },
{ label: 'Guangzhou', value: 'guangzhou' },
{ label: 'Shenzhen', value: 'shenzhen' }
]
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace v-for="type in types" :key="type" wrap>
<span class="row-label">{{ type }}</span>
<HuiSelect
v-model="value"
multiple
:max-collapse-tags="2"
:tag-type="type"
:options="options"
style="width: 320px"
/>
</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>
Selection Limit
Max limits the number of selections in multiple mode. Once reached, remaining unselected options become disabled.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect } from '@nscode/handy-ui'
const value = ref<string[]>([])
const options = [
{ label: 'Beijing', value: 'beijing' },
{ label: 'Shanghai', value: 'shanghai' },
{ label: 'Guangzhou', value: 'guangzhou' },
{ label: 'Shenzhen', value: 'shenzhen' }
]
</script>
<template>
<HuiSelect
v-model="value"
multiple
:max="2"
:options="options"
placeholder="Select up to 2 items"
/>
</template>
Select All and Clear
In multiple mode, select-all adds Select all and Clear buttons at the top. Select all includes only enabled options. Existing selections are retained, then unselected options are added in order. With max, additions stop at that limit and the buttons show selected count / max.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
const value = ref<string[]>([])
const limited = ref<string[]>(['shanghai'])
const options = [
{ label: 'Beijing', value: 'beijing' },
{ label: 'Shanghai', value: 'shanghai' },
{ label: 'Guangzhou', value: 'guangzhou' },
{ label: 'Shenzhen', value: 'shenzhen' },
{ label: 'Hangzhou (disabled)', value: 'hangzhou', disabled: true }
]
</script>
<template>
<HuiSpace wrap>
<HuiSelect v-model="value" multiple select-all :options="options" style="width: 320px" />
<HuiSelect
v-model="limited"
multiple
select-all
:max="3"
:options="options"
placeholder="Select all adds up to 3 selections"
style="width: 320px"
/>
</HuiSpace>
</template>
Search
Filterable allows typing while open, filtering labels by a case-insensitive substring match. Enter after typing selects the first result. No match displays the localized no-data message. With a current single selection, the search placeholder uses its label. In multiple mode, selecting clears the local query so another search can follow. Slot options are filtered too.
The examples demonstrate single, multiple and slot-based options:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSelectOption, HuiSpace } from '@nscode/handy-ui'
const value = ref<string>('banana')
const values = ref<string[]>([])
const slotValue = ref<string | null>(null)
const options = [
{ label: 'Apple', value: 'apple' },
{ label: 'Banana', value: 'banana' },
{ label: 'Peach', value: 'peach' },
{ label: 'Pineapple', value: 'pineapple' }
]
</script>
<template>
<HuiSpace wrap>
<HuiSelect
v-model="value"
filterable
:options="options"
placeholder="Type to search"
style="width: 200px"
/>
<HuiSelect
v-model="values"
filterable
multiple
:options="options"
placeholder="Try typing apple"
style="width: 280px"
/>
<HuiSelect
v-model="slotValue"
filterable
placeholder="Search slot options too"
style="width: 200px"
>
<HuiSelectOption
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</HuiSelect>
</HuiSpace>
</template>
Creating Options from Input
AllowCreate enables typing automatically without filterable. After trimming, a nonempty query with no exactly matching label displays a Create row first. Regular options, slot options and options created during the session all participate in duplicate-name detection. Reaching max in multiple mode hides creation. Numeric 1 and string '1' remain distinct by type.
After typing, the Create row is the first keyboard stop. Enter creates; up/down cycle through it and regular options. PageUp/PageDown move by the visible row count. Aria-activedescendant points only to a displayed, enabled row. With virtual scrolling, Create stays above the virtual list. While creation is pending, highlighting does not move and submissions do not repeat. IME composition keys do not create, and Home/End remain input-editing keys.
The default option is { label: query, value: query }. CreateMethod(query) can synchronously or asynchronously return a complete SelectOptionData. Disabled or incomplete results, throws and rejections neither select nor close. During an async operation, Create shows loading and the input becomes read only. Normal selection, Select all, Clear and repeated creation pause. Outside clicks or closing can still cancel the current creation session.
<script setup lang="ts">
import { onBeforeUnmount, ref, shallowRef } from 'vue'
import { HuiButton, HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type { SelectOptionData } from '@nscode/handy-ui'
const basic = ref<string | number | null>(null)
const limited = ref<(string | number)[]>([])
const coded = ref<string | number | null>(null)
const remoteValues = ref<(string | number)[]>([])
const saved = ref<string | number | null>(null)
const disabled = ref(false)
const nextOutcome = ref<'success' | 'failure'>('success')
const lastCreated = ref('None yet')
const status = ref(
'Type a new label and press Enter; choose the async outcome first, returned automatically after 600ms'
)
const options = ref<SelectOptionData[]>([{ label: 'Existing tag', value: 'known' }])
interface DemoCreateRequest {
query: string
timer: ReturnType<typeof setTimeout>
reject: (error: Error) => void
}
const pending = shallowRef<DemoCreateRequest>()
const requests = new Set<DemoCreateRequest>()
let seed = 100
const created = (option: SelectOptionData) => {
lastCreated.value = JSON.stringify(option)
status.value = 'A new option was generated and selection requested'
}
const createCode = (query: string): SelectOptionData => ({
label: `Code: ${query.toUpperCase()}`,
value: `code:${query}`
})
const search = (query: string): SelectOptionData[] =>
query.includes('api') ? [{ label: 'Existing api option', value: 'api' }] : []
const save = (query: string) =>
new Promise<SelectOptionData>((resolve, reject) => {
const success = nextOutcome.value === 'success'
const request: DemoCreateRequest = {
query,
reject,
timer: setTimeout(() => {
requests.delete(request)
if (pending.value === request) {
pending.value = undefined
status.value = success
? 'Simulated success; only the current valid creation request selects'
: 'Simulated save failure; input remains and creation can be retried'
}
if (success) {
resolve({ label: `Saved: ${query}`, value: ++seed })
} else {
reject(new Error('Simulated save failure'))
}
}, 600)
}
requests.add(request)
pending.value = request
status.value = `Saving ${query}; returns ${success ? 'success' : 'failure'} after 600ms`
})
const chooseOutcome = (outcome: 'success' | 'failure') => {
nextOutcome.value = outcome
status.value = `The next creation will ${outcome === 'success' ? 'succeed' : 'fail'} after 600ms`
}
const addExisting = () => {
if (options.value.some((option) => option.value === 'dynamic')) {
status.value = 'The dynamic option already exists'
return
}
options.value = [...options.value, { label: 'Dynamic option', value: 'dynamic' }]
status.value = 'Dynamic option added; entering the same label again does not create it'
}
onBeforeUnmount(() => {
for (const request of requests) {
clearTimeout(request.timer)
request.reject(new Error('Example unmounted'))
}
requests.clear()
})
</script>
<template>
<HuiSpace class="select-create-demo" direction="vertical" fill>
<span>Default single mode: type a new label; Existing tag does not show a Create row.</span>
<HuiSelect
v-model="basic"
class="create-basic"
allow-create
:options="options"
style="width: 320px; max-width: 100%"
@create="created"
/>
<HuiButton class="create-add-option" @click="addExisting">Add dynamic option</HuiButton>
<span>Multiple mode allows 2 items; numbers and strings retain distinct types.</span>
<HuiSelect
v-model="limited"
class="create-limited"
multiple
allow-create
:max="2"
:options="options"
style="width: 320px; max-width: 100%"
@create="created"
/>
<span
>The synchronous method returns a full label/value; Create stays above the virtual list
below.</span
>
<HuiSelect
v-model="coded"
class="create-coded"
allow-create
virtual
:create-method="createCode"
:options="options"
style="width: 320px; max-width: 100%"
@create="created"
/>
<span
>Remote search: type api for an existing option. After creation, change the query; selected
tags remain.</span
>
<HuiSelect
v-model="remoteValues"
class="create-remote"
multiple
allow-create
remote
:debounce="100"
:remote-method="search"
style="width: 360px; max-width: 100%"
@create="created"
/>
<span
>Async save: choose the next outcome, then type and create. Results return after 600ms without
another click. Failure neither selects nor closes; disabling invalidates the request.</span
>
<HuiSpace wrap>
<HuiButton
class="create-success"
:pressed="nextOutcome === 'success'"
:disabled="!!pending"
@click="chooseOutcome('success')"
>Next succeeds</HuiButton
>
<HuiButton
class="create-failure"
:pressed="nextOutcome === 'failure'"
:disabled="!!pending"
@click="chooseOutcome('failure')"
>Next fails</HuiButton
>
<HuiButton class="create-disable" @click="disabled = !disabled"
>Disabled: {{ disabled }}</HuiButton
>
</HuiSpace>
<HuiSelect
v-model="saved"
class="create-async"
allow-create
:disabled="disabled"
:create-method="save"
style="width: 320px; max-width: 100%"
@create="created"
/>
<span class="create-created">Creation notification: {{ lastCreated }}</span>
<span class="create-status" role="status">{{ status }}</span>
<span class="create-values"
>Single: {{ basic }}; multiple: {{ limited }}; synchronous: {{ coded }}; remote:
{{ remoteValues }}; saved: {{ saved }}</span
>
</HuiSpace>
</template>
Successful creation emits update:modelValue, change and create in order, then closes single mode or keeps multiple mode open. A parent may reject or normalize the selection; the actual model remains authoritative, while create still reports the successfully generated option. Its argument is a copy, so mutating it does not modify the internal cache. Options and slots remain reactive to application changes; current labels take precedence over cached ones. Created labels remain visible after a new remote batch arrives.
While pending, changes to the query, closing, data replacement, disabling, form read-only state, creation/remote configuration, selection mode, control mode, external model or unmounting invalidate an older creation. Stale results do not enter the cache, select or emit create. The caller owns any entity already saved by a business request. If a callback opens a new session, the old flow does not close it or clear its input.
Sizes
Size accepts large, default or small, matching HuiInput and HuiButton: heights 40 / 32 / 24px, font sizes 16 / 14 / 12px and radii 8 / 6 / 4px. Dropdown row heights are 40 / approximately 36 / 28px, with matching font sizes and horizontal padding 16 / 12 / 8px aligned to input text. Omitted size follows HuiFormItem, HuiForm and HuiConfigProvider, then default.
Each row compares clearable single selection, multiple selection and a matching button. Multiple tags use default tag size for large selectors and small tag size otherwise.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type { SelectOption } from '@nscode/handy-ui'
const value = ref<string>('beijing')
const values = ref<string[]>(['beijing', 'shanghai'])
const options: SelectOption[] = [
{ label: 'Beijing', value: 'beijing' },
{ label: 'Shanghai', value: 'shanghai' },
{ label: 'Guangzhou', value: 'guangzhou' }
]
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">large</span>
<HuiSelect v-model="value" size="large" clearable :options="options" style="width: 180px" />
<HuiSelect v-model="values" size="large" multiple :options="options" style="width: 260px" />
<HuiButton size="large">Button</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">default</span>
<HuiSelect v-model="value" clearable :options="options" style="width: 180px" />
<HuiSelect v-model="values" multiple :options="options" style="width: 260px" />
<HuiButton>Button</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">small</span>
<HuiSelect v-model="value" size="small" clearable :options="options" style="width: 180px" />
<HuiSelect v-model="values" size="small" multiple :options="options" style="width: 260px" />
<HuiButton size="small">Button</HuiButton>
</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>
Empty Data
Without options, the dropdown displays empty-text, defaulting to the localized no-data message. A query with no match displays no-match-text, falling back to empty-text when omitted. Use the empty slot for icons, links or other rich content; it takes precedence.
The first row customizes props: the left has no options, and the right can search for a nonexistent fruit such as Watermelon. The second row uses slots:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
const value = ref<string | null>(null)
const fruit = ref<string | null>(null)
const value2 = ref<string | null>(null)
const fruit2 = ref<string | null>(null)
const options = [
{ label: 'Apple', value: 'apple' },
{ label: 'Banana', value: 'banana' }
]
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<HuiSelect
v-model="value"
:options="[]"
empty-text="No categories added yet"
style="width: 240px"
/>
<HuiSelect
v-model="fruit"
filterable
:options="options"
no-match-text="Fruit not found"
placeholder="Try typing Watermelon"
style="width: 240px"
/>
</HuiSpace>
<HuiSpace wrap>
<HuiSelect v-model="value2" :options="[]" style="width: 240px">
<template #empty>No options available yet</template>
</HuiSelect>
<HuiSelect
v-model="fruit2"
filterable
:options="options"
placeholder="Slot: try typing Watermelon"
style="width: 240px"
>
<template #empty>Fruit not found. Try another query</template>
</HuiSelect>
</HuiSpace>
</HuiSpace>
</template>
Loading Options on Open
To avoid requesting options at page startup, fetch them on the first opening through visible-change. Set loading=true during the request. The dropdown shows a spinner and loading-text, using the localized loading message by default, instead of options. Both examples simulate a 1-second request; the right customizes its text to Fetching departments...:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type { SelectOption } from '@nscode/handy-ui'
const departments: SelectOption[] = [
{ label: 'Development', value: 'dev' },
{ label: 'Product', value: 'product' },
{ label: 'Operations', value: 'ops' }
]
const value = ref<string | null>(null)
const options = ref<SelectOption[]>([])
const loading = ref(false)
const value2 = ref<string | null>(null)
const options2 = ref<SelectOption[]>([])
const loading2 = ref(false)
const handleVisibleChange = (visible: boolean) => {
if (!visible || loading.value || options.value.length > 0) return
loading.value = true
setTimeout(() => {
options.value = departments
loading.value = false
}, 1000)
}
const handleVisibleChange2 = (visible: boolean) => {
if (!visible || loading2.value || options2.value.length > 0) return
loading2.value = true
setTimeout(() => {
options2.value = departments
loading2.value = false
}, 1000)
}
</script>
<template>
<HuiSpace wrap>
<HuiSelect
v-model="value"
:options="options"
:loading="loading"
placeholder="Open to load departments"
style="width: 240px"
@visible-change="handleVisibleChange"
/>
<HuiSelect
v-model="value2"
:options="options2"
:loading="loading2"
loading-text="Fetching departments..."
placeholder="Custom loading text"
style="width: 240px"
@visible-change="handleVisibleChange2"
/>
</HuiSpace>
</template>
Remote Search
For large datasets queried by keyword, enable remote and provide remote-method. Typing works on opening without filterable. After a debounce pause, 300ms by default, remote-method(query) is called. Clearing the query also calls it with an empty string, suitable for clearing options or restoring a default list. Local label filtering is disabled; the supplied options are displayed directly.
Remote-method supports two forms:
- Update props yourself: request data, write options and manage loading. The example simulates a 600ms request. Empty-text appears before querying and no-match-text when no results exist.
- Return results: return an array or Promise and let the component use it. A Promise automatically manages loading. A query change invalidates an old request immediately, including while the next debounce is pending. Old options managed through returned results are cleared and loading appears until the current result is available. See the following example.
With application-managed options/loading, the application must handle cancellation, ordering and loading state because the component cannot prevent assignments to those props. Use the returned array/Promise form for automatic isolation of stale results.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type { SelectOption } from '@nscode/handy-ui'
const cities = ['北京', '北海', '北戴河', '上海', '上饶', '广州', '广元', '深圳', '杭州', '南京']
const value = ref<string | null>(null)
const options = ref<SelectOption[]>([])
const loading = ref(false)
const remoteMethod = (query: string) => {
if (!query) {
options.value = []
return
}
loading.value = true
// Simulate an API with setTimeout, returning cities whose names contain the query
setTimeout(() => {
options.value = cities
.filter((city) => city.includes(query))
.map((city) => ({ label: city, value: city }))
loading.value = false
}, 600)
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSelect
v-model="value"
remote
:remote-method="remoteMethod"
:options="options"
:loading="loading"
clearable
placeholder="Type the sample query 北 or 上"
empty-text="Enter a city name to search"
no-match-text="No matching cities"
style="width: 240px"
/>
<span>Selected value: {{ value === null ? 'null' : (value ?? 'undefined') }}</span>
</HuiSpace>
</template>
In multiple remote mode, selecting retains the query and current results so more items from the same batch can be selected. Local search instead clears the query. Selected labels are cached, so a later result batch that omits them does not turn tags into raw values.
The following remote-method returns a Promise without managing options or loading. It sets debounce to 500ms and loading-text to Searching.... Search Development and select two people, then search Product; the earlier tags retain their labels:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type { SelectOption } from '@nscode/handy-ui'
const staff: SelectOption[] = [
{ label: 'Development - Zhang San', value: 1 },
{ label: 'Development - Li Si', value: 2 },
{ label: 'Development - Wang Wu', value: 3 },
{ label: 'Product - Zhao Liu', value: 4 },
{ label: 'Product - Qian Qi', value: 5 },
{ label: 'Operations - Sun Ba', value: 6 }
]
const values = ref<number[]>([])
// Return a Promise: the component manages loading and options. Simulate an 800ms API with setTimeout
const searchStaff = (query: string) =>
new Promise<SelectOption[]>((resolve) => {
setTimeout(() => {
resolve(query ? staff.filter((item) => item.label.includes(query)) : [])
}, 800)
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSelect
v-model="values"
multiple
remote
:remote-method="searchStaff"
:debounce="500"
loading-text="Searching..."
placeholder="Type Development, Product or a name"
empty-text="Enter a query to search people"
style="max-width: 360px"
/>
<span>Selected value: {{ JSON.stringify(values) }}</span>
</HuiSpace>
</template>
Virtual Scrolling
For thousands or tens of thousands of options, virtual renders only the visible handful and replaces them as scrolling proceeds. Keyboard navigation scrolls the highlighted item into view, and opening single mode scrolls to the selected item. It works with search, multiple mode, Select all, max and remote search.
Virtual scrolling applies only to options, not slot-based HuiSelectOption children. Slot options still render fully and produce a development notice. Rows default to a fixed height of 40px for large, 36px for default and 28px for small. A positive finite itemSize overrides that height; regular lists ignore it. The dropdown matches the trigger width, truncating long labels.
The script below generates 10,000 options, disabling one in every seven:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type { SelectOption } from '@nscode/handy-ui'
const options: SelectOption[] = Array.from({ length: 10000 }, (_, index) => ({
label: `Option ${index + 1}`,
value: index + 1,
disabled: (index + 1) % 7 === 0
}))
const value = ref<number>(5000)
const values = ref<number[]>([1, 2, 3])
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<HuiSelect
v-model="value"
virtual
filterable
clearable
:options="options"
style="width: 240px"
/>
<HuiSelect
v-model="values"
virtual
multiple
filterable
select-all
:options="options"
placeholder="Select all 10,000 items"
style="width: 320px"
/>
</HuiSpace>
<span
>Single: {{ value === null ? 'null' : (value ?? 'undefined') }}; multiple selected:
{{ values.length }} items</span
>
</HuiSpace>
</template>
Virtual also supports large remote result sets. Type any query below; the simulated API returns 5,000 results:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect } from '@nscode/handy-ui'
import type { SelectOption } from '@nscode/handy-ui'
const value = ref<string | null>(null)
// Simulate an API with setTimeout, returning 5,000 results for any query
const search = (query: string) =>
new Promise<SelectOption[]>((resolve) => {
setTimeout(() => {
resolve(
query
? Array.from({ length: 5000 }, (_, index) => ({
label: `${query} - Result ${index + 1}`,
value: `${query}-${index + 1}`
}))
: []
)
}, 500)
})
</script>
<template>
<HuiSelect
v-model="value"
virtual
remote
:remote-method="search"
placeholder="Type any search query"
empty-text="Typing returns 5,000 results"
style="width: 280px"
/>
</template>
Grouped data also supports virtual scrolling. Each group heading and leaf takes one physical row controlled by itemSize. Headings do not count as logical options: aria-setsize and aria-posinset count filtered leaves, with a visible creation row retaining its existing first-item position. This example switches between 44px, 56px, and 400px rows; the last is taller than the default viewport.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSelect, HuiSpace } from '@nscode/handy-ui'
const value = ref<string | number | null>(null)
const rowHeight = ref(44)
const groups = Array.from({ length: 3 }, (_, group) => ({
label: `Group ${group + 1}`,
options: Array.from({ length: 30 }, (_, index) => ({
value: `g${group + 1}-${index + 1}`,
label: `Group ${group + 1}, item ${index + 1}`
}))
}))
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiButton @click="rowHeight = rowHeight === 44 ? 56 : rowHeight === 56 ? 400 : 44"
>Virtual row height: {{ rowHeight }}px</HuiButton
>
<HuiSelect
v-model="value"
:options="groups"
virtual
:item-size="rowHeight"
style="width: 320px"
/>
<span role="status">Selected: {{ value ?? 'Empty' }}</span>
</HuiSpace>
</template>
Focus Boundaries and Native Events
Focus and blur report entry into and exit from the whole group, retaining native FocusEvent objects during normal movement. The search input and teleported panel toolbar belong to that group, so internal movement does not repeat events. If closing removes search without a focusout, a blur is synthesized based on final focus. Focus() respects component and form disabled/read-only states. Blur() moves focus only within this group. Captured methods have no effect after unmounting. Focus movement does not change the model.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSelect, HuiSpace, HuiTimeSelect } from '@nscode/handy-ui'
import type { SelectExpose } from '@nscode/handy-ui'
const selectRef = ref<SelectExpose>()
const timeRef = ref<Pick<SelectExpose, 'focus' | 'blur'>>()
const disabled = ref(false)
const selectEvents = ref<string[]>([])
const timeEvents = ref<string[]>([])
const options = [
{ label: 'A', value: 'a' },
{ label: 'B', value: 'b' }
]
const log = (events: string[], type: string, event: FocusEvent) => {
events.push(`${type}(${event.type})`)
}
</script>
<template>
<HuiSpace class="select-focus-demo" direction="vertical" fill>
<span
>Entry and exit notify once; movement within search and the panel toolbar does not repeat
notifications or change selection.</span
>
<HuiSpace wrap>
<HuiButton class="focus-select" @click="selectRef?.focus()">Focus selector</HuiButton>
<HuiButton class="blur-select" @click="selectRef?.blur()">Blur selector</HuiButton>
<HuiButton class="focus-time" @click="timeRef?.focus()">Focus time selector</HuiButton>
<HuiButton class="toggle-disabled" @click="disabled = !disabled">{{
disabled ? 'Enable' : 'Disable'
}}</HuiButton>
</HuiSpace>
<HuiSelect
ref="selectRef"
class="focus-choice"
multiple
select-all
filterable
:disabled="disabled"
:options="options"
@focus="(event) => log(selectEvents, 'focus', event)"
@blur="(event) => log(selectEvents, 'blur', event)"
/>
<p class="select-focus-events" role="status">
Selector: {{ selectEvents.join(' → ') || 'No focus movement yet' }}
</p>
<HuiTimeSelect
ref="timeRef"
class="focus-time-choice"
filterable
:disabled="disabled"
@focus="(event) => log(timeEvents, 'focus', event)"
@blur="(event) => log(timeEvents, 'blur', event)"
/>
<p class="time-focus-events" role="status">
Time selector: {{ timeEvents.join(' → ') || 'No focus movement yet' }}
</p>
<HuiButton class="focus-outside">External focus target</HuiButton>
</HuiSpace>
</template>
Events
Change reports user-driven value changes. Visible-change reports opening and closing. Remove-tag reports tag close-icon removal. Select-all reports Select all, while clear reports the clear icon or toolbar Clear. Recent events appear below:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
const value = ref<string[]>(['beijing'])
const logs = ref<string[]>([])
const options = [
{ label: 'Beijing', value: 'beijing' },
{ label: 'Shanghai', value: 'shanghai' },
{ label: 'Guangzhou', value: 'guangzhou' },
{ label: 'Shenzhen', value: 'shenzhen' }
]
const log = (text: string) => {
logs.value = [text, ...logs.value].slice(0, 6)
}
const onChange = (val: unknown) => log(`change:${JSON.stringify(val)}`)
const onVisibleChange = (visible: boolean) => log(`visible-change:${visible}`)
const onRemoveTag = (val: string | number) => log(`remove-tag:${val}`)
const onSelectAll = (vals: (string | number)[]) => log(`select-all:${JSON.stringify(vals)}`)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSelect
v-model="value"
multiple
clearable
select-all
:options="options"
style="max-width: 360px"
@change="onChange"
@visible-change="onVisibleChange"
@remove-tag="onRemoveTag"
@select-all="onSelectAll"
@clear="log('clear')"
/>
<div class="logs">
<div v-if="logs.length === 0">No events yet</div>
<div v-for="(item, index) in logs" :key="index">{{ item }}</div>
</div>
</HuiSpace>
</template>
<style scoped>
.logs {
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
Calling Methods
Call focus() and blur() through a ref. When filtering and already open, focus() targets search. FilteredOptions exposes options filtered by the current query, without local filtering in remote mode. Open and type below to inspect it:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSelect, HuiSpace } from '@nscode/handy-ui'
const selectRef = ref<InstanceType<typeof HuiSelect>>()
const value = ref<string | null>(null)
const options = [
{ label: 'Beijing', value: 'beijing' },
{ label: 'Shanghai', value: 'shanghai' },
{ label: 'Guangzhou', value: 'guangzhou' },
{ label: 'Shenzhen', value: 'shenzhen' }
]
</script>
<template>
<HuiSpace wrap>
<HuiSelect ref="selectRef" v-model="value" filterable :options="options" style="width: 240px" />
<HuiButton @click="selectRef?.focus()">Focus (focus)</HuiButton>
<HuiButton @click="selectRef?.blur()">Blur (blur)</HuiButton>
</HuiSpace>
<p style="margin-top: 12px">
filteredOptions:{{ selectRef?.filteredOptions.map((item) => item.label).join('、') }}
</p>
</template>
Candidate Originals and Actual Selection
The second change(value, selected) argument contains original option records for that request: one object in single mode, undefined for single clearing, or an independent array shell in multiple mode. Business metadata and original object references are retained. Zero, empty strings, numbers and identically written strings remain distinct.
When a controlled parent rejects or normalizes a request, the event still reports its candidate. Ref.selectedOptions queries originals in actual model order. It and filteredOptions return a new array shell on each read; records themselves are neither cloned nor frozen. After remote options change, originals remain cached for actual selections and latest candidates. Unknown values and slot options receive standard value/label query records without creating extra selectable rows.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type {
SelectExpose,
SelectOptionData,
SelectSelected,
SelectValue
} from '@nscode/handy-ui'
const options: SelectOptionData[] = [
{ value: 0, label: 'Numeric zero', department: '研发' },
{ value: '0', label: 'String zero', department: '产品' },
{ value: '', label: 'Empty string', department: '公共' }
]
const actual = ref<SelectValue>(0)
const select = ref<SelectExpose>()
const candidate = ref('None yet')
const original = ref('None yet')
const changed = (value: SelectValue, selected: SelectSelected) => {
candidate.value = JSON.stringify(value) ?? 'undefined'
original.value = JSON.stringify(selected) ?? 'undefined'
}
</script>
<template>
<HuiSpace class="select-option-context-demo" direction="vertical" fill>
<span
>The first selector uses two-way binding; the second fixes numeric zero to compare candidates
with actual originals.</span
>
<HuiSpace wrap>
<HuiSelect
v-model="actual"
class="select-context-bound"
:options="options"
clearable
style="width: 220px"
@change="changed"
/>
<HuiSelect
ref="select"
class="select-context-fixed"
:model-value="0"
:options="options"
clearable
style="width: 220px"
@change="changed"
/>
</HuiSpace>
<span class="select-context-actual">Bound value: {{ JSON.stringify(actual) }}</span>
<span class="select-context-candidate">Current candidate: {{ candidate }}</span>
<span class="select-context-original">Candidate originals: {{ original }}</span>
<span class="select-context-selected">
Fixed selector actual originals: {{ JSON.stringify(select?.selectedOptions ?? []) }}
</span>
</HuiSpace>
</template>
Public Clear Method
Ref.clear() uses the same entry point as the clear icon and dropdown toolbar without requiring clearable. It emits update:modelValue → clear → change, requesting null in single mode or [] in multiple mode. Controlled parents may reject or normalize it; queries and display still reflect the actual model. Disabled, form read-only, pending creation and unmounted instances do not submit. An old clear operation interrupted through synchronous reentry does not continue sending stale notifications.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type { SelectExpose, SelectValue } from '@nscode/handy-ui'
const options = [
{ value: 0, label: 'Zero' },
{ value: 1, label: 'One' }
]
const single = ref<SelectValue>(1)
const multiple = ref<SelectValue>([0, 1])
const singleRef = ref<SelectExpose>()
const multipleRef = ref<SelectExpose>()
const fixedRef = ref<SelectExpose>()
const disabled = ref(false)
const requested = ref('None yet')
const record = (value: SelectValue) => {
requested.value = JSON.stringify(value) ?? 'undefined'
}
</script>
<template>
<HuiSpace class="select-clear-method-demo" direction="vertical" fill>
<HuiSpace wrap>
<HuiSelect
ref="singleRef"
v-model="single"
:options="options"
:disabled="disabled"
style="width: 160px"
/>
<HuiButton class="select-clear-single" @click="singleRef?.clear()"
>Clear single selection</HuiButton
>
<HuiButton class="select-clear-disabled" @click="disabled = !disabled"
>Toggle disabled: {{ disabled }}</HuiButton
>
</HuiSpace>
<HuiSpace wrap>
<HuiSelect
ref="multipleRef"
v-model="multiple"
multiple
:options="options"
style="width: 240px"
/>
<HuiButton class="select-clear-multiple" @click="multipleRef?.clear()"
>Clear multiple selection</HuiButton
>
</HuiSpace>
<HuiSpace wrap>
<HuiSelect
ref="fixedRef"
class="select-clear-fixed-field"
:model-value="1"
:options="options"
style="width: 160px"
@update:model-value="record"
/>
<HuiButton class="select-clear-fixed" @click="fixedRef?.clear()"
>Parent rejects clearing</HuiButton
>
</HuiSpace>
<span class="select-clear-values"
>Actual single: {{ JSON.stringify(single) }}; actual multiple:
{{ JSON.stringify(multiple) }}</span
>
<span class="select-clear-request">Rejected parent requests only notify: {{ requested }}</span>
</HuiSpace>
</template>
Within a Form
Inside HuiFormItem, value changes trigger change rules, dropdown closing triggers blur rules, and omitted size/disabled follow the form. Open the city dropdown and close without selecting to see the required-field message:
<script setup lang="ts">
import { reactive, ref } from 'vue'
import {
HuiButton,
HuiForm,
HuiFormItem,
HuiMessage,
HuiSelect,
HuiSpace
} from '@nscode/handy-ui'
import type { FormRule } from '@nscode/handy-ui'
const formRef = ref<InstanceType<typeof HuiForm>>()
const model = reactive<{ city?: string | null; tags: string[] }>({ city: undefined, tags: [] })
const rules: Record<string, FormRule[]> = {
city: [{ required: true, message: 'Choose a city', trigger: ['change', 'blur'] }],
tags: [{ required: true, message: 'Select at least one tag', trigger: 'change' }]
}
const cities = [
{ label: 'Beijing', value: 'beijing' },
{ label: 'Shanghai', value: 'shanghai' }
]
const tags = [
{ label: 'Frontend', value: 'fe' },
{ label: 'Backend', value: 'be' },
{ label: 'Testing', value: 'qa' }
]
const submit = async () => {
const result = await formRef.value?.validate()
if (result?.valid) HuiMessage.success('Validation passed')
}
</script>
<template>
<HuiForm ref="formRef" :model="model" :rules="rules" label-width="80px" style="max-width: 420px">
<HuiFormItem label="City" prop="city">
<HuiSelect v-model="model.city" :options="cities" clearable />
</HuiFormItem>
<HuiFormItem label="Tags" prop="tags">
<HuiSelect v-model="model.tags" :options="tags" multiple clearable />
</HuiFormItem>
<HuiFormItem>
<HuiSpace>
<HuiButton type="primary" @click="submit">Submit</HuiButton>
<HuiButton @click="formRef?.resetFields()">Reset</HuiButton>
</HuiSpace>
</HuiFormItem>
</HuiForm>
</template>
Keyboard Interaction
Use Tab to focus the selector. Once focused:
| Key | Action |
|---|---|
| Enter / Space | Opens if closed; otherwise selects the highlighted option, or closes if none is highlighted |
| ↓ / ↑ | Opens if closed; otherwise navigates options, skipping disabled items and wrapping |
| Esc | Closes the dropdown and returns focus to the selector |
| Tab | Closes and moves focus to the next element |
In searchable or remote mode, Space enters text instead of selecting. Typing highlights the first match, and Enter selects it; remote results also begin at the first item. During loading, arrows do not move and Enter does not close; wait for results. Virtual scrolling automatically reveals an offscreen highlighted item.
PageUp/PageDown move one visible page without wrapping; before an item is active, they choose the last/first available item respectively. Page size comes from measured rows, or ten rows when measurement is unavailable; virtual lists use their viewport and row height. Home/End choose the first/last enabled item only in a non-editable selector. Searchable, remote and creation inputs keep Home/End, text and spaces for native editing.
In a non-editable list, characters match label prefixes. Characters entered within 500ms form a word, while repeated identical characters cycle through matches. Data replacement or reordering keeps the active value and its type when still available. A removed, disabled or hidden item yields to a nearby enabled option. Hidden/inert slot options and wrappers hidden by CSS are skipped. Virtual navigation first reveals the target, then links the actual focused element's aria-activedescendant to its rendered row.
Loading or pending asynchronous creation blocks navigation and selection without closing on Enter. IME composition, key code 229, Ctrl/Meta/Alt shortcuts, and already-consumed events are ignored.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiSelect, HuiSpace } from '@nscode/handy-ui'
const plain = ref<number | null>(null)
const searchable = ref<number | null>(null)
const virtual = ref<number | null>(null)
const options = Array.from({ length: 30 }, (_, index) => ({
label: ['Alpha', 'Alpine', 'Beta', 'Bravo', 'Charlie'][index % 5] + ' ' + (index + 1),
value: index + 1,
disabled: index === 0 || index === 14
}))
</script>
<template>
<HuiSpace class="select-keyboard-demo" direction="vertical" fill>
<HuiSelect
v-model="plain"
:options="options"
placeholder="Plain list"
style="width: 280px; max-width: 100%; flex: none"
/>
<HuiSelect
v-model="searchable"
filterable
:options="options"
placeholder="Searchable list"
style="width: 280px; max-width: 100%; flex: none"
/>
<HuiSelect
v-model="virtual"
virtual
:options="options"
placeholder="Virtual list"
style="width: 280px; max-width: 100%; flex: none"
/>
<span role="status"
>Selected: plain {{ plain ?? 'Empty' }}; search {{ searchable ?? 'Empty' }}; virtual
{{ virtual ?? 'Empty' }}</span
>
</HuiSpace>
</template>
HuiSelect Props
remoteMethod can be passed inline. To invalidate an in-flight request, such as after changing data sources, change remote or recreate the component with a new key.
Recreate the component with a new key when changing the algorithm of a props mapping function.
| Prop | Type | Default | Description |
|---|---|---|---|
| modelValue | string | number | (string | number)[] | null | - | Controlled when supplied, including undefined/null as empty; otherwise internal, even with only an update listener. Single mode binds a value, multiple mode an array |
| options | readonly object[] | null | undefined | — | Original records. An explicitly supplied source takes precedence over default-slot options, including empty [], undefined and null |
| props | SelectFieldNames | — | Field names or original-record getters for value, label, children and disabled; children defaults to options |
| multiple | boolean | false | Whether multiple selection is enabled |
| disabled | boolean | false | Whether the selector is disabled |
| clearable | boolean | false | Whether to show the clear button when nonempty |
| filterable | boolean | false | Whether to search option labels |
| allowCreate | boolean | false | Enables creating options from typed input, also enabling typing |
| createMethod | SelectCreateMethod | - | Synchronously or asynchronously creates a complete option from the trimmed query |
| placeholder | string | Localized selection prompt | Placeholder text |
| size | 'large' | 'default' | 'small' | 'default' | Size |
| collapseTags | boolean | true | Whether extra multiple tags collapse into +N |
| maxCollapseTags | number | 3 | Maximum visible tags before collapsing |
| max | number | - | Multiple-selection limit, unlimited when omitted |
| selectAll | boolean | false | Whether multiple mode shows Select all and Clear in its toolbar |
| tagType | 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'help' | 'primary' | Multiple tag type |
| validateEvent | boolean | true | Whether value changes and dropdown closing trigger form-item validation |
| remote | boolean | false | Enables typing and remoteMethod requests without local filtering |
| remoteMethod | SelectRemoteMethod | - | Search function taking the query, returning an option array or Promise |
| debounce | number | 300 | Remote-search pause in milliseconds before calling remoteMethod |
| loading | boolean | false | Shows a spinner and loadingText instead of options |
| loadingText | string | Localized loading message | Loading text |
| emptyText | string | Localized no-data message | Empty-options text, overridden by the empty slot |
| noMatchText | string | - | Unmatched-query text, falling back to emptyText |
| virtual | boolean | false | Renders visible options only. Applies only to options data |
| itemSize | number | By size | Positive finite virtual row height, shared by headings and leaves; ignored by regular lists |
HuiSelectOption Props
| Prop | Type | Default | Description |
|---|---|---|---|
| label | string | - | Required display label, used after selection and for filtering |
| value | string | number | - | Required option value |
| disabled | boolean | false | Whether this option is disabled |
| selected | boolean | - | Forces its selected appearance. Usually omitted; defaults to the HuiSelect model |
HuiSelectOptionGroup Props
| Prop | Type | Default | Description |
|---|---|---|---|
| label | string | Required | Group name, connected to role=group by a heading ID; the heading is not selectable |
| disabled | boolean | false | Disables the group and descendants; false on a descendant cannot override an ancestor's true |
HuiSelectOptionGroup Slots
| Slot | Scope | Description |
|---|---|---|
| default | — | HuiSelectOption children or nested groups; groups without visible leaves are hidden after registration |
HuiSelect Events
| Event | Callback Arguments | Description |
|---|---|---|
| focus | (event: FocusEvent) | Entry into the whole group, without repeated internal transitions |
| blur | (event: FocusEvent) | Exit from the whole group, preserving the native event |
| update:modelValue | (value: string | number | (string | number)[] | null) | Value changes, used by v-model |
| change | (value: SelectValue, selected: SelectSelected) | Candidate value and original records for the user action. Still reports a rejected candidate; query properties reflect actual selection |
| clear | — | Clear icon, toolbar or clear() requests clearing; event order is update, clear, change |
| visibleChange | (visible: boolean) | Dropdown opens or closes |
| removeTag | (value: string | number) | Multiple tag close icon removes an item, with its value |
| selectAll | (values: (string | number)[]) | Select all is clicked, with resulting values |
| create | (option: SelectOptionData) | A generated option requests selection. Argument is a copy; emitted even if the parent rejects selection |
HuiSelect Slots
| Slot | Scope Arguments | Description |
|---|---|---|
| default | - | HuiSelectOption or HuiSelectOptionGroup children when options is omitted and no automatic remote result is active |
| empty | - | No visible options, using emptyText or noMatchText by default |
| option | SelectOptionSlotProps | Data leaf body: original option, selected, disabled and index; role, interaction and check mark stay component-managed |
| header | SelectPanelSlotProps | Fixed header, retained for empty data; receives close() |
| footer | SelectPanelSlotProps | Fixed footer, retained for empty data; receives close() |
HuiSelectOption Slots
| Slot | Scope Arguments | Description |
|---|---|---|
| default | - | Custom option content, otherwise label |
Methods
Call through an HuiSelect ref.
| Method | Arguments | Return Value | Description |
|---|---|---|---|
| focus | - | void | Focuses the selector, or search when filtering and already open |
| blur | - | void | Blurs the selector |
| clear | - | void | Requests null in single mode or [] in multiple mode through the shared entry point. Controlled parents may reject; disabled/read-only states prevent it |
filteredOptions is read only and returns original leaf records filtered by the current query, excluding group headings and internal normalized records. Remote mode does not filter locally, and returned remoteMethod results are used when provided.
selectedOptions is readonly SelectRawOption[], reporting originals in actual model order. Both queries return independent array shells on every read while retaining original-record references.
Types
import type {
SelectExpose,
SelectFieldNames,
SelectOption,
SelectOptionData,
SelectProps,
SelectRawOption,
SelectOptionGroupProps,
SelectOptionSlotProps,
SelectPanelSlotProps,
SelectSlots,
SelectRemoteMethod,
SelectSelected,
SelectSize,
SelectValue
} from '@nscode/handy-ui'
interface SelectOption {
label: string
value: string | number
disabled?: boolean
}
interface SelectOptionData extends SelectOption, Record<string, unknown> {}
type SelectCreateMethod = (query: string) => SelectOptionData | Promise<SelectOptionData>
type SelectRawOption = Record<string, unknown>
type SelectValue = string | number | (string | number)[] | null
type SelectSelected = SelectRawOption | SelectRawOption[] | undefined
interface SelectExpose {
focus: () => void
blur: () => void
clear: () => void
readonly filteredOptions: readonly SelectRawOption[]
readonly selectedOptions: readonly SelectRawOption[]
}
type SelectSize = 'large' | 'default' | 'small'
/**
* Remote-search function taking the query, or an empty string after clearing the query.
* Without a return value, manage options and loading yourself. Return an array or Promise for component-managed options;
* loading is automatic while a Promise is pending. Query changes immediately invalidate old results, including during debounce;
* Closing, disabling or changing remote settings rejects old results. Application-managed props still require application-managed requests.
*/
type SelectRemoteMethod = (
query: string
) => void | readonly object[] | Promise<readonly object[] | void>
SelectFieldNames accepts optional field names or original-record getters for value, label, children, and disabled. SelectOptionSlotProps contains option: SelectRawOption, selected: boolean, disabled: boolean, and index: number. SelectPanelSlotProps contains only close: () => void. These types are exported from @nscode/handy-ui; API record arrays do not need an added index signature.