AutoComplete
Shows suggestions while typing and fills the input when one is selected. Use it for search, addresses, product names and other fields that allow both free text and candidate selection. Use HuiSelect when values must come only from options.
Import
import { HuiAutoComplete } from '@nscode/handy-ui'
Basic Usage
Bind the text with v-model. fetch-suggestions receives a function that returns suggestions for the current input. By default, focusing requests suggestions immediately, and typing requests them after a 300ms pause. Use arrow keys to navigate, Enter to select and Esc to close, or choose with the mouse.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const value = ref('')
const restaurants = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶']
const fetchSuggestions: AutoCompleteFetchSuggestions = (query) =>
restaurants.filter((name) => name.includes(query))
</script>
<template>
<HuiAutoComplete
v-model="value"
:fetch-suggestions="fetchSuggestions"
placeholder="Enter a restaurant name"
/>
</template>
Suggestions may be strings or objects shaped as { value, label?, disabled? }. Selection fills the input with label, or value when there is no label; see Choosing the Display Field.
Async Suggestions
The function may return a Promise. A loading icon appears at the right of the input while it is pending. With successive inputs, only the latest request's result is used; older results arriving later are discarded. A result arriving after blur does not reopen the dropdown.
The example simulates an 800ms API request with setTimeout. Replace it with your actual request:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions, AutoCompleteSuggestion } from '@nscode/handy-ui'
const value = ref('')
const shops = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶', '茶百道', '喜茶']
// In an application: const res = await fetch(`/api/shops?keyword=${query}`); return res.json()
const fetchSuggestions: AutoCompleteFetchSuggestions = (query) =>
new Promise<AutoCompleteSuggestion[]>((resolve) => {
setTimeout(() => {
resolve(shops.filter((name) => name.includes(query)).map((name) => ({ value: name })))
}, 800)
})
</script>
<template>
<HuiAutoComplete
v-model="value"
:fetch-suggestions="fetchSuggestions"
placeholder="Try typing 茶"
style="width: 280px"
/>
</template>
Callback Form
Alternatively, call the second argument, callback, after receiving results. The function then does not need to return anything.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const value = ref('')
const restaurants = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶']
const fetchSuggestions: AutoCompleteFetchSuggestions = (query, callback) => {
setTimeout(() => callback(restaurants.filter((name) => name.includes(query))), 300)
}
</script>
<template>
<HuiAutoComplete v-model="value" :fetch-suggestions="fetchSuggestions" style="width: 280px" />
</template>
Static Suggestions
suggestions accepts an array directly. The component does not filter this array by the input; all items remain visible. Pass a computed value for filtering, or a function with the same contract as fetch-suggestions. When both are supplied, suggestions takes precedence.
The left example passes an unfiltered array. The right passes a computed value filtered by the input:
<script setup lang="ts">
import { computed, ref } from 'vue'
import { HuiAutoComplete, HuiSpace } from '@nscode/handy-ui'
const raw = ref('')
const value = ref('')
const fruits = ['苹果', '香蕉', '橙子', '葡萄']
const filtered = computed(() => fruits.filter((item) => item.includes(value.value)))
</script>
<template>
<HuiSpace wrap>
<HuiAutoComplete
v-model="raw"
:suggestions="fruits"
placeholder="Array: unfiltered"
style="width: 240px"
/>
<HuiAutoComplete
v-model="value"
:suggestions="filtered"
placeholder="computed: filtered by input"
style="width: 240px"
/>
</HuiSpace>
</template>
Choosing the Display Field
When a suggestion object has no label, value-key selects the field used for display and insertion. It defaults to 'value'. Suggestions may include arbitrary business fields, accessible in the select event and suggestion slot.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions, AutoCompleteSuggestion } from '@nscode/handy-ui'
const value = ref('')
const code = ref<unknown>()
const cities = [
{ value: 110000, name: '北京' },
{ value: 310000, name: '上海' }
]
const fetchCities: AutoCompleteFetchSuggestions = (query) =>
cities.filter((city) => city.name.includes(query))
const handleSelect = (item: AutoCompleteSuggestion) => {
code.value = item.value
}
</script>
<template>
<HuiAutoComplete
v-model="value"
:fetch-suggestions="fetchCities"
value-key="name"
style="width: 280px"
@select="handleSelect"
/>
<p style="margin-top: 12px">
Input: {{ value || '(empty)' }}; city code: {{ code ?? '(not selected)' }}
</p>
</template>
Custom Suggestion Content
Use the suggestion slot to render each item. Its scope is { suggestion, index }.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const value = ref('')
const shops = [
{ value: '新旺角茶餐厅', address: '长宁区淞虹路 661 号' },
{ value: '港式小厨', address: '普陀区真北路 988 号' },
{ value: '胖仙女', address: '闵行区虹莘路 3388 号' },
{ value: '贡茶', address: '徐汇区漕溪北路 331 号' }
]
const fetchShops: AutoCompleteFetchSuggestions = (query) =>
shops.filter((shop) => shop.value.includes(query))
</script>
<template>
<HuiAutoComplete v-model="value" :fetch-suggestions="fetchShops">
<template #suggestion="{ suggestion }">
<div>{{ suggestion.label }}</div>
<div class="address">{{ suggestion.address }}</div>
</template>
</HuiAutoComplete>
</template>
<style scoped>
.address {
font-size: 12px;
color: var(--hui-text-color-secondary);
}
</style>
Empty Results
With an empty slot, the dropdown opens even without suggestions and displays that slot. Without it, no suggestions means no dropdown.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const value = ref('')
const restaurants = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶']
const fetchSuggestions: AutoCompleteFetchSuggestions = (query) =>
restaurants.filter((name) => name.includes(query))
</script>
<template>
<HuiAutoComplete v-model="value" :fetch-suggestions="fetchSuggestions">
<template #empty>
<div style="padding: 8px 12px">No matching restaurants</div>
</template>
</HuiAutoComplete>
</template>
Disabled Suggestions
An object with disabled: true appears muted. Arrow navigation skips it, and neither clicks nor Enter can select it.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const value = ref('')
const fetchSuggestions: AutoCompleteFetchSuggestions = () => [
{ value: '新旺角茶餐厅' },
{ value: '港式小厨', label: 'Hong Kong Kitchen (closed)', disabled: true },
{ value: '胖仙女' }
]
</script>
<template>
<HuiAutoComplete
v-model="value"
:fetch-suggestions="fetchSuggestions"
placeholder="Focus, then try the arrow keys"
style="width: 280px"
/>
</template>
Disabling Suggestions on Focus
trigger-on-focus defaults to true, immediately requesting suggestions for the current input, which may be empty. Set it to false to request only after typing. Focus the two inputs below to compare:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete, HuiSpace } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const value = ref('')
const other = ref('')
const restaurants = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶']
const fetchSuggestions: AutoCompleteFetchSuggestions = (query) =>
restaurants.filter((name) => name.includes(query))
</script>
<template>
<HuiSpace wrap>
<HuiAutoComplete
v-model="value"
:fetch-suggestions="fetchSuggestions"
placeholder="Opens on focus (true)"
style="width: 240px"
/>
<HuiAutoComplete
v-model="other"
:fetch-suggestions="fetchSuggestions"
:trigger-on-focus="false"
placeholder="Opens after typing (false)"
style="width: 240px"
/>
</HuiSpace>
</template>
Debounce
debounce sets the delay after typing before requesting suggestions, defaulting to 300ms. Focus requests do not wait. Type quickly below and compare the request counts:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete, HuiSpace } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const fast = ref('')
const slow = ref('')
const fastCount = ref(0)
const slowCount = ref(0)
const words = ['apple', 'apricot', 'banana', 'blueberry', 'cherry']
const fetchFast: AutoCompleteFetchSuggestions = (query) => {
fastCount.value += 1
return words.filter((word) => word.includes(query))
}
const fetchSlow: AutoCompleteFetchSuggestions = (query) => {
slowCount.value += 1
return words.filter((word) => word.includes(query))
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<HuiAutoComplete
v-model="fast"
:fetch-suggestions="fetchFast"
:debounce="0"
:trigger-on-focus="false"
placeholder="debounce 0"
style="width: 200px"
/>
<span>Requests made: {{ fastCount }} requests</span>
</HuiSpace>
<HuiSpace wrap>
<HuiAutoComplete
v-model="slow"
:fetch-suggestions="fetchSlow"
:debounce="1000"
:trigger-on-focus="false"
placeholder="debounce 1000"
style="width: 200px"
/>
<span>Requests made: {{ slowCount }} requests</span>
</HuiSpace>
</HuiSpace>
</template>
Selecting Without a Match
With select-when-unmatched: true, pressing Enter without a highlighted suggestion still emits select, whether there are no results or no arrow-key selection. The argument is { value: currentInput, label: currentInput }. This supports search inputs that submit directly on Enter.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete, HuiMessage } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const keyword = ref('')
const restaurants = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶']
const fetchSuggestions: AutoCompleteFetchSuggestions = (query) =>
restaurants.filter((name) => name.includes(query))
const search = (text?: string) => {
HuiMessage(`Search for ${text}`)
}
</script>
<template>
<HuiAutoComplete
v-model="keyword"
:fetch-suggestions="fetchSuggestions"
select-when-unmatched
@select="(item) => search(item.label)"
/>
</template>
Clearable
With clearable: true and nonempty content, a native clear button appears with a localized accessible name and Tab, Enter, and Space support. It requests '', then emits update:modelValue, input, clear, and change in that order. Suggestions close; input focus is restored only while focus still belongs to this control, without taking external focus.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const value = ref('港式小厨')
const restaurants = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶']
const fetchSuggestions: AutoCompleteFetchSuggestions = (query) =>
restaurants.filter((name) => name.includes(query))
</script>
<template>
<HuiAutoComplete v-model="value" :fetch-suggestions="fetchSuggestions" clearable />
</template>
Prefix and Suffix Icons
prefix-icon and suffix-icon accept icon names. The suffix is hidden while loading or while the clear button is displayed. In the third input below, clearing its content reveals the suffix icon.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete, HuiSpace } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const prefix = ref('')
const suffix = ref('')
const both = ref('港式小厨')
const restaurants = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶']
const fetchSuggestions: AutoCompleteFetchSuggestions = (query) =>
restaurants.filter((name) => name.includes(query))
</script>
<template>
<HuiSpace wrap>
<HuiAutoComplete
v-model="prefix"
:fetch-suggestions="fetchSuggestions"
prefix-icon="search"
placeholder="Prefix icon"
style="width: 200px"
/>
<HuiAutoComplete
v-model="suffix"
:fetch-suggestions="fetchSuggestions"
suffix-icon="location"
placeholder="Suffix icon"
style="width: 200px"
/>
<HuiAutoComplete
v-model="both"
:fetch-suggestions="fetchSuggestions"
prefix-icon="search"
suffix-icon="location"
clearable
placeholder="Prefix, suffix and clear button"
style="width: 200px"
/>
</HuiSpace>
</template>
Loading State
When loading is omitted, the component shows the loading icon during requests automatically. Providing it overrides this behavior and gives you control. hide-loading: true always hides the loading icon.
All three requests below take 1 second. The first manages the icon automatically. The second follows loading and keeps it visible while checked. The third uses hide-loading and never shows it during the request.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete, HuiCheckbox, HuiSpace } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const auto = ref('')
const manual = ref('')
const hidden = ref('')
const loading = ref(false)
const restaurants = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶']
// Simulate a 1-second request
const fetchSuggestions: AutoCompleteFetchSuggestions = (query) =>
new Promise<string[]>((resolve) => {
setTimeout(() => resolve(restaurants.filter((name) => name.includes(query))), 1000)
})
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<HuiAutoComplete
v-model="auto"
:fetch-suggestions="fetchSuggestions"
placeholder="Automatic indicator"
style="width: 200px"
/>
<HuiAutoComplete
v-model="manual"
:fetch-suggestions="fetchSuggestions"
:loading="loading"
placeholder="Controlled by loading"
style="width: 200px"
/>
<HuiAutoComplete
v-model="hidden"
:fetch-suggestions="fetchSuggestions"
hide-loading
placeholder="hide-loading"
style="width: 200px"
/>
</HuiSpace>
<HuiCheckbox v-model="loading">Show loading for the second input (loading)</HuiCheckbox>
</HuiSpace>
</template>
Placement
placement controls the dropdown position, defaulting to 'bottom-start', with 12 supported positions. It flips when space is insufficient, and the dropdown is at least as wide as the input. Focus each input below to compare:
<script setup lang="ts">
import { reactive } from 'vue'
import { HuiAutoComplete, HuiSpace } from '@nscode/handy-ui'
const values = reactive<Record<string, string>>({})
const suggestions = ['新旺角茶餐厅', '港式小厨', '贡茶']
</script>
<template>
<div class="placements">
<div class="placements__row placements__row--center">
<HuiAutoComplete
v-for="item in ['top-start', 'top', 'top-end']"
:key="item"
v-model="values[item]"
:suggestions="suggestions"
:placement="item"
:placeholder="item"
style="width: 140px"
/>
</div>
<div class="placements__row placements__row--between">
<HuiSpace direction="vertical" align="start">
<HuiAutoComplete
v-for="item in ['left-start', 'left', 'left-end']"
:key="item"
v-model="values[item]"
:suggestions="suggestions"
:placement="item"
:placeholder="item"
style="width: 140px"
/>
</HuiSpace>
<HuiSpace direction="vertical" align="end">
<HuiAutoComplete
v-for="item in ['right-start', 'right', 'right-end']"
:key="item"
v-model="values[item]"
:suggestions="suggestions"
:placement="item"
:placeholder="item"
style="width: 140px"
/>
</HuiSpace>
</div>
<div class="placements__row placements__row--center">
<HuiAutoComplete
v-for="item in ['bottom-start', 'bottom', 'bottom-end']"
:key="item"
v-model="values[item]"
:suggestions="suggestions"
:placement="item"
:placeholder="item"
style="width: 140px"
/>
</div>
</div>
</template>
<style scoped>
.placements {
max-width: 560px;
margin: 0 auto;
}
.placements__row {
display: flex;
gap: var(--hui-spacing-2);
}
.placements__row--center {
justify-content: center;
}
.placements__row--between {
justify-content: space-between;
margin: var(--hui-spacing-3) 0;
}
</style>
Disabled and Read Only
disabled prevents typing. With readonly, users can focus and copy but not type, and focusing does not request suggestions. Both states hide the clear button. The component follows the enclosing HuiForm's disabled state.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete, HuiSpace } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const empty = ref('')
const value = ref('新旺角茶餐厅')
const restaurants = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶']
const fetchSuggestions: AutoCompleteFetchSuggestions = (query) =>
restaurants.filter((name) => name.includes(query))
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">disabled</span>
<HuiAutoComplete v-model="empty" disabled placeholder="Disabled" style="width: 200px" />
<HuiAutoComplete
v-model="value"
:fetch-suggestions="fetchSuggestions"
disabled
clearable
prefix-icon="search"
style="width: 200px"
/>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">readonly</span>
<HuiAutoComplete v-model="empty" readonly placeholder="Read only" style="width: 200px" />
<HuiAutoComplete
v-model="value"
:fetch-suggestions="fetchSuggestions"
readonly
clearable
prefix-icon="search"
style="width: 200px"
/>
</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>
Sizes
size accepts large, default or small. Input heights are 40, 32 and 24px; font sizes 16, 14 and 12px; radii 8, 6 and 4px; and icons 18, 16 and 14px, matching HuiInput. Dropdown row heights are 40, 36 and 28px, with font sizes 16, 14 and 12px and horizontal padding 16, 12 and 8px, aligned with the input text. Within HuiForm, size follows the form.
Each row compares an AutoComplete with a prefix icon and clear button, an Input and a Button of the same size:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete, HuiButton, HuiInput, HuiSpace } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const value = ref('新旺角茶餐厅')
const text = ref('')
const restaurants = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶']
const fetchSuggestions: AutoCompleteFetchSuggestions = (query) =>
restaurants.filter((name) => name.includes(query))
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">large</span>
<HuiAutoComplete
v-model="value"
:fetch-suggestions="fetchSuggestions"
size="large"
prefix-icon="search"
clearable
style="width: 220px"
/>
<HuiInput v-model="text" size="large" placeholder="Input" style="width: 160px" />
<HuiButton size="large">Button</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">default</span>
<HuiAutoComplete
v-model="value"
:fetch-suggestions="fetchSuggestions"
prefix-icon="search"
clearable
style="width: 220px"
/>
<HuiInput v-model="text" placeholder="Input" style="width: 160px" />
<HuiButton>Button</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">small</span>
<HuiAutoComplete
v-model="value"
:fetch-suggestions="fetchSuggestions"
size="small"
prefix-icon="search"
clearable
style="width: 220px"
/>
<HuiInput v-model="text" size="small" placeholder="Input" style="width: 160px" />
<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>
Input Length
maxlength limits typed characters, but not text inserted by selecting a suggestion. minlength is a native attribute used only by native form validation.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const value = ref('')
const codes = ['SH600000', 'SH600036', 'SZ000001', 'SZ000002']
const fetchCodes: AutoCompleteFetchSuggestions = (query) =>
codes.filter((code) => code.includes(query.toUpperCase()))
</script>
<template>
<HuiAutoComplete
v-model="value"
:fetch-suggestions="fetchCodes"
:maxlength="8"
placeholder="Enter up to 8 characters"
style="width: 240px"
/>
</template>
Events
Typing emits input together with update:modelValue. Selecting emits input, change and select in order. Clearing emits input, clear, and change in order. focus and blur report input focus entry and exit. Recent events appear below:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete, HuiSpace } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions, AutoCompleteSuggestion } from '@nscode/handy-ui'
const value = ref('')
const logs = ref<string[]>([])
const restaurants = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶']
const fetchSuggestions: AutoCompleteFetchSuggestions = (query) =>
restaurants.filter((name) => name.includes(query))
const log = (text: string) => {
logs.value = [text, ...logs.value].slice(0, 6)
}
const onInput = (val: string) => log(`input:${val}`)
const onChange = (val: string) => log(`change:${val}`)
const onSelect = (item: AutoCompleteSuggestion) => log(`select:${item.label}`)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiAutoComplete
v-model="value"
:fetch-suggestions="fetchSuggestions"
clearable
style="max-width: 320px"
@input="onInput"
@change="onChange"
@select="onSelect"
@clear="log('clear')"
@focus="log('focus')"
@blur="log('blur')"
/>
<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. inputRef exposes the internal <input> element for native methods such as select() to select all text.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete, HuiButton, HuiSpace } from '@nscode/handy-ui'
import type { AutoCompleteExpose, AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const autoRef = ref<AutoCompleteExpose>()
const value = ref('港式小厨')
const restaurants = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶']
const fetchSuggestions: AutoCompleteFetchSuggestions = (query) =>
restaurants.filter((name) => name.includes(query))
</script>
<template>
<HuiSpace wrap>
<HuiAutoComplete
ref="autoRef"
v-model="value"
:fetch-suggestions="fetchSuggestions"
:trigger-on-focus="false"
style="width: 240px"
/>
<HuiButton @click="autoRef?.focus()">Focus (focus)</HuiButton>
<HuiButton @click="autoRef?.blur()">Blur (blur)</HuiButton>
<HuiButton @click="autoRef?.inputRef?.select()">Select text (inputRef.select)</HuiButton>
</HuiSpace>
</template>
Within a Form
Inside HuiFormItem, changes from typing, selection and clearing trigger change rules; input blur triggers blur rules. Selecting a suggestion does not blur the input. The label is associated with the input through for. Set :validate-event="false" to disable validation triggers.
<script setup lang="ts">
import { reactive } from 'vue'
import { HuiAutoComplete, HuiForm, HuiFormItem } from '@nscode/handy-ui'
import type { AutoCompleteFetchSuggestions } from '@nscode/handy-ui'
const model = reactive({ city: '' })
const cities = ['北京', '上海', '广州', '深圳', '杭州']
const fetchCities: AutoCompleteFetchSuggestions = (query) =>
cities.filter((city) => city.includes(query))
</script>
<template>
<HuiForm
:model="model"
:rules="{ city: [{ required: true, message: 'Enter a city', trigger: 'blur' }] }"
>
<HuiFormItem label="City" prop="city">
<HuiAutoComplete v-model="model.city" :fetch-suggestions="fetchCities" />
</HuiFormItem>
</HuiForm>
</template>
Internal Text and Controlled Updates
When modelValue is omitted or only its update event is observed, the component keeps its own text through input, selection, clearing, and unrelated parent renders. Supplying the prop makes it controlled, including explicit undefined as empty text. Display, clear-button state, and form validation follow the actual parent value after acceptance, normalization, or rejection. Switching control modes produces a development diagnostic and restores the original internal text.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete, HuiButton, HuiSpace } from '@nscode/handy-ui'
import type { AutoCompleteExpose } from '@nscode/handy-ui'
const control = ref<AutoCompleteExpose>()
const redraw = ref(0)
const recent = ref('No selection')
const choices = ['Alpha', 'Beta', 'Gamma']
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace
><HuiButton @click="redraw++">Parent renders: {{ redraw }}</HuiButton
><HuiButton @click="control?.clear()">Clear text</HuiButton></HuiSpace
>
<HuiAutoComplete
ref="control"
:suggestions="choices"
:debounce="0"
clearable
@select="recent = String($event.value)"
/>
<HuiAutoComplete model-value="Fixed text" :suggestions="choices" />
<HuiAutoComplete
:model-value="undefined"
:suggestions="choices"
placeholder="Controlled empty text"
/>
<span>Recent selection: {{ recent }}</span>
</HuiSpace>
</template>
Groups and Fixed Header/Footer
Suggestions may mix ordinary items with { label, options, disabled? } groups. An object is a group only when it has an options array and no value; ordinary suggestions can retain their own business field named options. Returned arrays, Promises, and callbacks also support groups. Group headings are not selectable; disabled groups keep their items visible but unavailable. Static arrays filter child labels and hide empty groups. Function results are not filtered again. Keyboard navigation and ARIA counts include suggestions, excluding group headings.
header and footer stay outside the scrollable list and receive close(). They do not open an empty list by themselves: suggestions or an empty slot are still required. Tab enters the first interactive header/footer control; Shift+Tab from that control returns to the input. Internal focus movement does not produce duplicate focus/blur events.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAutoComplete, HuiButton, HuiSpace } from '@nscode/handy-ui'
import type { AutoCompleteSuggestionList } from '@nscode/handy-ui'
const value = ref('')
const recent = ref('No selection')
const groups: AutoCompleteSuggestionList = [
{
label: 'Customers',
options: [
{ value: 'a', label: 'Customer A' },
{ value: 'b', label: 'Customer B' }
]
},
{ label: 'Disabled suppliers', disabled: true, options: [{ value: 'c', label: 'Supplier C' }] }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiAutoComplete
v-model="value"
:suggestions="groups"
:debounce="0"
@select="recent = String($event.value)"
>
<template #header>Grouped business records</template>
<template #footer="{ close }"
><HuiButton @click="close">Close suggestions</HuiButton></template
>
<template #empty>No matching records</template>
</HuiAutoComplete>
<span>Text: {{ value }}; recent selection: {{ recent }}</span>
</HuiSpace>
</template>
Keyboard Interaction
Up/Down cycle through available suggestions; there is initially no highlight. PageUp/PageDown move by the measured visible row count, or ten items when measurement is unavailable, without wrapping. Enter selects the highlighted item; without one, selectWhenUnmatched applies. Home/End and left/right remain text-caret keys. Tab enters a header/footer control when available, otherwise closes suggestions and moves focus normally.
Composition, key code 229, Alt/Ctrl/Meta combinations, and already consumed keys are ignored. Navigation identity follows each original item and its occurrence: strings by text, objects by identity. Reordering preserves the active item; filtering, disabling, or removal selects a nearby available item. Duplicate values are retained, with independent navigation and ARIA identities. Closing removes aria-activedescendant.
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| modelValue | string | undefined | Controlled whenever supplied, including explicit undefined as empty; internally saved when omitted. |
| placeholder | string | Localized input prompt | Placeholder text |
| disabled | boolean | false | Whether the component is disabled |
| readonly | boolean | false | Read-only state. Focus does not request suggestions |
| clearable | boolean | false | Whether to show a clear button with nonempty content |
| size | 'large' | 'default' | 'small' | - | Follows the form, or default outside one |
| fetchSuggestions | AutoCompleteFetchSuggestions | - | Fetch function returning an array or Promise, or calling its callback |
| suggestions | AutoCompleteSuggestionsInput | - | Static ordinary/grouped items or a fetch function returning them; takes precedence over fetchSuggestions. |
| loading | boolean | undefined | Loading indicator. Automatically follows requests when omitted |
| valueKey | string | 'value' | Display and insertion field when a suggestion has no label |
| placement | PopperPlacement | 'bottom-start' | Dropdown position; flips when space is insufficient |
| debounce | number | 300 | Delay in milliseconds after typing before fetching. Focus requests do not wait |
| triggerOnFocus | boolean | true | Whether focus requests suggestions immediately |
| selectWhenUnmatched | boolean | false | Whether Enter emits select without a highlighted suggestion |
| hideLoading | boolean | false | Whether to hide the loading icon |
| maxlength | number | - | Maximum typed length |
| minlength | number | - | Native minimum input length |
| prefixIcon | string | - | Prefix icon name |
| suffixIcon | string | - | Suffix icon name, hidden while loading or showing the clear button |
| validateEvent | boolean | true | Whether value changes and blur trigger form-item validation |
| popperClass | string | - | Additional class on the suggestion popup. |
Events
| Event | Callback Arguments | Description |
|---|---|---|
| update:modelValue | (value: string) | Typing, selection or clearing. Does not emit during IME composition; emits once on commit |
| input | (value: string) | Emitted with update:modelValue |
| change | (value: string) | Selection or clearing, and native change after edited content is committed through blur or Enter |
| focus | (event: FocusEvent) | Input gains focus |
| blur | (event: FocusEvent) | Input loses focus. Clicking a suggestion or dropdown does not blur it |
| clear | - | Emitted after the clear button is clicked |
| select | (suggestion: AutoCompleteSuggestion) | Selected suggestion, including its label. See selectWhenUnmatched for unmatched input |
Slots
| Slot | Scope Arguments | Description |
|---|---|---|
| suggestion | { suggestion: AutoCompleteSuggestion; index: number } | Custom suggestion rendering. Defaults to suggestion.label |
| empty | - | Content without suggestions. Providing this slot allows the dropdown to open with no results |
| header | { close: () => void } | Fixed header outside the scrollable options. |
| footer | { close: () => void } | Fixed footer outside the scrollable options. |
Methods
| Name | Type | Description |
|---|---|---|
| focus | () => void | Focuses the input |
| blur | () => void | Blurs the input |
| inputRef | HTMLInputElement | Internal input element |
| clear | () => void | Same request as the clear button; inactive when disabled, readonly, or unmounted. Controlled values await parent acceptance. |
Types
import type {
AutoCompleteProps,
AutoCompleteEmits,
AutoCompleteExpose,
AutoCompleteSize,
AutoCompleteSuggestion,
AutoCompleteSuggestionGroup,
AutoCompleteSuggestionData,
AutoCompleteSuggestionList,
AutoCompletePanelSlotProps,
AutoCompleteSlots,
AutoCompleteFetchSuggestions,
AutoCompleteFetchSuggestionsResult,
AutoCompleteSuggestionsInput,
PopperPlacement
} from '@nscode/handy-ui'
type AutoCompleteSize = 'large' | 'default' | 'small'
interface AutoCompleteSuggestion {
value: string | number | object
/** Display text; defaults to item[valueKey] */
label?: string
disabled?: boolean
/** Additional business fields are allowed */
[key: string]: unknown
}
interface AutoCompleteSuggestionGroup {
label: string
options: Array<string | AutoCompleteSuggestion>
disabled?: boolean
[key: string]: unknown
}
type AutoCompleteSuggestionData = string | AutoCompleteSuggestion | AutoCompleteSuggestionGroup
type AutoCompleteSuggestionList = AutoCompleteSuggestionData[]
type AutoCompleteFetchSuggestionsResult =
| AutoCompleteSuggestionList
| Promise<AutoCompleteSuggestionList>
type AutoCompleteFetchSuggestions = (
query: string,
callback: (suggestions: AutoCompleteSuggestionList) => void
) => AutoCompleteFetchSuggestionsResult | void
type AutoCompleteSuggestionsInput =
| AutoCompleteSuggestionList
| AutoCompleteSuggestion
| AutoCompleteSuggestionGroup
| AutoCompleteFetchSuggestions
interface AutoCompletePanelSlotProps {
close: () => void
}
type PopperPlacement =
| 'top'
| 'top-start'
| 'top-end'
| 'bottom'
| 'bottom-start'
| 'bottom-end'
| 'left'
| 'left-start'
| 'left-end'
| 'right'
| 'right-start'
| 'right-end'
interface AutoCompleteExpose {
focus: () => void
blur: () => void
clear: () => void
inputRef: HTMLInputElement | undefined
}
AutoCompleteProps and AutoCompleteEmits correspond to the Props and Events tables above.