AutoComplete 自動完成
輸入時在下方顯示建議清單,選取後將建議文字填入輸入框。適合搜尋、地址或商品名稱等「可自由輸入,也可從候選選取」的情境;只允許選項時請使用 HuiSelect。
引入
import { HuiAutoComplete } from '@nscode/handy-ui'
基礎用法
以 v-model 綁定輸入文字,透過 fetch-suggestions 傳入依輸入內容產生建議的函式。預設聚焦時立即請求一次,之後每次輸入停止 300 毫秒再請求。上下鍵移動、Enter 選取、Esc 關閉,也可用滑鼠點選。
<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="請輸入餐廳名稱"
/>
</template>
建議可以是字串,也可以是物件 { value, label?, disabled? }。選中後輸入框裡填的是 label,沒有 label 時是 value(見“指定顯示欄位”)。
非同步獲取建議
函式可回傳 Promise;請求期間輸入框右側顯示載入圖示。連續輸入時只採用最後一次請求,先發後到的舊結果直接丟棄;輸入框失焦後才回來的結果不會再次打開面板。
<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 = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶', '茶百道', '喜茶']
// 實際項目裡: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="輸入“茶”試試"
style="width: 280px"
/>
</template>
回呼寫法
也可以拿到結果後呼叫第二個參數 callback,這時函式不用返回任何東西。
<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>
靜態資料
suggestions 可直接傳陣列,依顯示文字(label,未設定時取 valueKey 欄位或 value)進行不區分大小寫的包含比對。computed 回傳的陣列仍依同一規則比對;需要完全自訂結果時傳入函式(寫法與 fetch-suggestions 相同),函式結果不會再追加篩選。suggestions 與 fetch-suggestions 同時傳入時,以 suggestions 為準。
左側直接傳入靜態陣列,右側由 computed 預先處理陣列;兩者都依顯示文字比對目前輸入:
<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="陣列:依文字篩選"
style="width: 240px"
/>
<HuiAutoComplete
v-model="value"
:suggestions="filtered"
placeholder="computed:預先處理陣列"
style="width: 240px"
/>
</HuiSpace>
</template>
指定顯示欄位
建議物件沒有 label 時,value-key 指定用哪個欄位作為顯示和填入的文字,預設是 'value'。建議物件可以帶任意業務欄位,在 select 事件和 suggestion 插槽裡都能拿到。
<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">
輸入框裡:{{ value || '(空)' }};城市編碼:{{ code ?? '(未選擇)' }}
</p>
</template>
自訂建議項
用 suggestion 插槽自訂每一項的內容,作用域參數是 { 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 插槽時,沒有建議也會打開下拉,顯示插槽內容;不寫時沒有建議就不彈出。
<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">沒有找到相關餐廳</div>
</template>
</HuiAutoComplete>
</template>
禁用建議項
建議物件設定 disabled: true 時顯示為灰色,上下鍵會跳過,點擊和 Enter 都不能選取。
<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: '港式小廚(已打烊)', disabled: true },
{ value: '胖仙女' }
]
</script>
<template>
<HuiAutoComplete
v-model="value"
:fetch-suggestions="fetchSuggestions"
placeholder="聚焦後用上下鍵試試"
style="width: 280px"
/>
</template>
聚焦時不彈出
trigger-on-focus 預設為 true,聚焦時立即以目前內容(可為空字串)請求一次建議。設為 false 後,只有輸入內容才會請求。
<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="聚焦就彈出(true)"
style="width: 240px"
/>
<HuiAutoComplete
v-model="other"
:fetch-suggestions="fetchSuggestions"
:trigger-on-focus="false"
placeholder="輸入後才彈出(false)"
style="width: 240px"
/>
</HuiSpace>
</template>
防抖時間
debounce 是輸入後等待多久才請求建議,預設 300 毫秒;聚焦時的首次請求不等待。
<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>已請求 {{ fastCount }} 次</span>
</HuiSpace>
<HuiSpace wrap>
<HuiAutoComplete
v-model="slow"
:fetch-suggestions="fetchSlow"
:debounce="1000"
:trigger-on-focus="false"
placeholder="debounce 1000"
style="width: 200px"
/>
<span>已請求 {{ slowCount }} 次</span>
</HuiSpace>
</HuiSpace>
</template>
沒有匹配時Enter也選中
select-when-unmatched=true 且沒有醒目建議時,Enter 仍會觸發 select,參數為 { value: 目前輸入, label: 目前輸入 }。適合按 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(`搜尋“${text}”`)
}
</script>
<template>
<HuiAutoComplete
v-model="keyword"
:fetch-suggestions="fetchSuggestions"
select-when-unmatched
@select="(item) => search(item.label)"
/>
</template>
可清除
clearable=true 且有內容時顯示原生清除按鈕,可用 Tab、Enter 或空白操作。點選後請求空字串 '',依序通知 update:modelValue、input、clear、change 並關閉面板;焦點仍屬本控制項時才恢復輸入框,不搶外部焦點。
<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-icon、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="前綴圖示"
style="width: 200px"
/>
<HuiAutoComplete
v-model="suffix"
:fetch-suggestions="fetchSuggestions"
suffix-icon="location"
placeholder="後綴圖示"
style="width: 200px"
/>
<HuiAutoComplete
v-model="both"
:fetch-suggestions="fetchSuggestions"
prefix-icon="search"
suffix-icon="location"
clearable
placeholder="前後綴和清除"
style="width: 200px"
/>
</HuiSpace>
</template>
載入狀態
不傳 loading 時,元件在請求期間自動顯示載入圖示;傳了 loading 就以它為準,由你自己控制。hide-loading 為 true 時始終不顯示載入圖示。
下面三個輸入框的請求都要 1 秒:第一個自動顯示載入圖示;第二個用 loading 控制,勾選後一直顯示;第三個加了 hide-loading,請求期間也不顯示。
<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 = ['新旺角茶餐厅', '港式小厨', '胖仙女', '贡茶']
// 模擬 1 秒的請求
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="自動顯示"
style="width: 200px"
/>
<HuiAutoComplete
v-model="manual"
:fetch-suggestions="fetchSuggestions"
:loading="loading"
placeholder="由 loading 控制"
style="width: 200px"
/>
<HuiAutoComplete
v-model="hidden"
:fetch-suggestions="fetchSuggestions"
hide-loading
placeholder="hide-loading"
style="width: 200px"
/>
</HuiSpace>
<HuiCheckbox v-model="loading">第二個顯示載入中(loading)</HuiCheckbox>
</HuiSpace>
</template>
彈出位置
placement 指定下拉面板的位置,預設 'bottom-start',共 12 個方向。放不下時自動翻到另一側,下拉面板寬度至少和輸入框一樣。點一下下面的輸入框,看下拉面板出現在哪:
<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 停用輸入;readonly 仍可聚焦與複製,但不能輸入,聚焦時也不請求建議。兩種狀態都不顯示清除按鈕;置於 HuiForm 時跟隨表單停用。
<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="禁用" 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="唯讀" 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>
尺寸
size 可選 large、default、small:輸入框高度分別是 40、32、24px,字級 16、14、12px,圓角 8、6、4px,圖示 18、16、14px,和同尺寸的 HuiInput 一致;下拉面板的選項跟著變,列高 40、36、28px,字級 16、14、12px,左右內距 16、12、8px(和輸入框裡的文字左邊對齊)。在 HuiForm 裡時跟隨表單的尺寸。
每一行是一種尺寸,依次是帶前綴圖示和清除按鈕的自動完成、同尺寸的輸入框和按鈕:
<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="輸入框" style="width: 160px" />
<HuiButton size="large">按鈕</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="輸入框" style="width: 160px" />
<HuiButton>按鈕</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="輸入框" style="width: 160px" />
<HuiButton size="small">按鈕</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>
輸入長度
maxlength 限制最多能輸入幾個字,選中建議填入的文字不受它限制;minlength 是原生屬性,只在原生表單驗證時起作用。
<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="最多輸入 8 個字元"
style="width: 240px"
/>
</template>
事件
輸入時通知 input 與 update:modelValue;選取建議時依序通知 input、change、select;清除時依序通知 input、clear、change;取得與離開焦點時通知 focus、blur。
<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">還沒有觸發事件</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>
呼叫方法
通過 ref 呼叫 focus()、blur();inputRef 是內部的 <input> 元素,可以直接呼叫它的原生方法,例如 select() 選中全部文字。
<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)</HuiButton>
<HuiButton @click="autoRef?.blur()">失焦(blur)</HuiButton>
<HuiButton @click="autoRef?.inputRef?.select()">選中文字(inputRef.select)</HuiButton>
</HuiSpace>
</template>
在表單裡使用
置於 HuiFormItem 時,輸入、選取與清除造成的值變更會觸發 change 規則,失焦觸發 blur 規則;選取建議時輸入框不會先失焦。表單標籤透過 for 關聯輸入框。不需驗證時設定 :validate-event="false"。
<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: '請填寫城市', trigger: 'blur' }] }"
>
<HuiFormItem label="城市" prop="city">
<HuiAutoComplete v-model="model.city" :fetch-suggestions="fetchCities" />
</HuiFormItem>
</HuiForm>
</template>
自持文字與受控回填
未傳 modelValue 或僅監聽更新時,元件自行保存輸入、選取與清除後的文字,父元件無關重新呈現不會重置。傳入屬性即受控,明確 undefined 亦表示受控空文字。父元件接受、改寫或拒絕請求後,輸入框、清除按鈕及表單驗證均依實際值收斂;切換控制方式會發出開發診斷並恢復原內部文字。
<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('尚無選取')
const choices = ['Alpha', 'Beta', 'Gamma']
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace
><HuiButton @click="redraw++">父元件重新呈現:{{ redraw }}</HuiButton
><HuiButton @click="control?.clear()">清除文字</HuiButton></HuiSpace
>
<HuiAutoComplete
ref="control"
:suggestions="choices"
:debounce="0"
clearable
@select="recent = String($event.value)"
/>
<HuiAutoComplete model-value="固定文字" :suggestions="choices" />
<HuiAutoComplete :model-value="undefined" :suggestions="choices" placeholder="受控空文字" />
<span>最近選取:{{ recent }}</span>
</HuiSpace>
</template>
分組與固定頭尾
建議可混合普通項與 { label, options, disabled? } 分組。僅有 options 陣列且不含 value 的物件才表示組;普通建議可保留名為 options 的業務欄位。函式、Promise 與回呼同樣支援分組。組名不可選,禁用組的子項仍可見但不可操作。靜態陣列依子項文字篩選並隱藏空組,函式結果不再二次篩選。鍵盤與 ARIA 計數只包含建議項。
header、footer 固定在捲動清單之外,均提供 close()。頭尾不會自行展開空清單,仍需建議項或 empty 插槽。Tab 進入頭尾第一個互動控制項,該項按 Shift+Tab 回到輸入框;內部移焦不會重複發出 focus/blur。
<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('尚無選取')
const groups: AutoCompleteSuggestionList = [
{
label: '客戶',
options: [
{ value: 'a', label: '甲客戶' },
{ value: 'b', label: '乙客戶' }
]
},
{ label: '停用供應商', disabled: true, options: [{ value: 'c', label: '丙供應商' }] }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiAutoComplete
v-model="value"
:suggestions="groups"
:debounce="0"
@select="recent = String($event.value)"
>
<template #header>依業務物件分組</template>
<template #footer="{ close }"><HuiButton @click="close">收起建議</HuiButton></template>
<template #empty>沒有符合的業務物件</template>
</HuiAutoComplete>
<span>文字:{{ value }};最近選取:{{ recent }}</span>
</HuiSpace>
</template>
鍵盤操作
上下鍵循環移動高亮並跳過禁用項,預設無高亮。PageUp/PageDown 依可見列數翻頁,無法量測時為十項且不循環。Enter 選取高亮項,未高亮時依 selectWhenUnmatched 處理。Home/End、左右鍵留給文字游標。Tab 在有頭尾控制項時進入首項,否則收起建議並正常移焦。
輸入法組合、鍵碼 229、Alt/Ctrl/Meta 組合與已消費按鍵不處理。內部身分依原建議項與出現次數保存:字串按文字、物件按身分;重排保留目前項,篩選、禁用或移除時就近回退。同值建議不會去重,每次出現均有獨立導航與 ARIA 識別。關閉後移除 aria-activedescendant。
Props
| 屬性 | 類型 | 預設值 | 說明 |
|---|---|---|---|
| modelValue | string | undefined | 傳入即受控,明確undefined為空;未傳時自行保存文字 |
| placeholder | string | 隨語言(中文:請輸入) | 提示文字 |
| disabled | boolean | false | 是否禁用 |
| readonly | boolean | false | 是否唯讀。唯讀時聚焦不請求建議 |
| clearable | boolean | false | 有內容時是否顯示清除圖示 |
| size | 'large' | 'default' | 'small' | - | 尺寸。不傳時跟隨表單,不在表單裡時是 'default' |
| fetchSuggestions | AutoCompleteFetchSuggestions | - | 獲取建議的函式,可以返回陣列、返回 Promise 或呼叫 callback |
| suggestions | AutoCompleteSuggestionsInput | - | 普通或分組的靜態資料,或返回相同資料的函式;優先於fetchSuggestions |
| loading | boolean | undefined | 是否顯示載入圖示。不傳時元件在請求期間自動顯示 |
| valueKey | string | 'value' | 建議物件沒有 label 時,用哪個欄位作為顯示和填入的文字 |
| placement | PopperPlacement | 'bottom-start' | 下拉面板的位置,放不下時自動翻到另一側 |
| debounce | number | 300 | 輸入後等多少毫秒再請求建議。聚焦時的請求不等待 |
| triggerOnFocus | boolean | true | 聚焦時是否立即請求建議 |
| selectWhenUnmatched | boolean | false | 沒有醒目的建議時,按Enter是否也觸發 select |
| hideLoading | boolean | false | 是否隱藏載入圖示 |
| maxlength | number | - | 最大輸入長度 |
| minlength | number | - | 最小輸入長度(原生屬性) |
| prefixIcon | string | - | 前綴圖示名 |
| suffixIcon | string | - | 後綴圖示名。載入中、顯示清除圖示時不顯示 |
| validateEvent | boolean | true | 值變化和失焦時是否觸發所在表單項的驗證 |
| popperClass | string | - | 建議浮層的附加類別 |
Events
| 事件 | 回呼參數 | 說明 |
|---|---|---|
| update:modelValue | (value: string) | 輸入、選中建議、清除時觸發。輸入法組合期間不觸發,確認輸入後觸發一次 |
| input | (value: string) | 和 update:modelValue 同時觸發 |
| change | (value: string) | 選中建議、點清除按鈕時觸發;也是原生 change,內容有變化後失焦或按Enter時觸發 |
| focus | (event: FocusEvent) | 輸入框獲得焦點時觸發 |
| blur | (event: FocusEvent) | 輸入框失去焦點時觸發。點建議、點下拉面板不會讓輸入框失焦 |
| clear | - | 點清除按鈕後觸發 |
| select | (suggestion: AutoCompleteSuggestion) | 選中建議時觸發,參數是整個建議物件(帶上了 label);selectWhenUnmatched 時見上面的說明 |
Slots
| 插槽 | 作用域參數 | 說明 |
|---|---|---|
| suggestion | { suggestion: AutoCompleteSuggestion; index: number } | 自訂每一項建議的內容,預設顯示 suggestion.label |
| empty | - | 沒有建議時顯示的內容。寫了它,沒有結果時也會打開下拉 |
| header | { close: () => void } | 固定於選項捲動區之外的頭部 |
| footer | { close: () => void } | 固定於選項捲動區之外的尾部 |
方法
| 名稱 | 類型 | 說明 |
|---|---|---|
| focus | () => void | 讓輸入框獲得焦點 |
| blur | () => void | 讓輸入框失去焦點 |
| inputRef | HTMLInputElement | 內部的 input 元素 |
| clear | () => void | 與清除按鈕共用請求;禁用、唯讀或卸載後無效,受控時等待父回填 |
類型
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
/** 顯示的文字;不寫時顯示 item[valueKey] */
label?: string
disabled?: boolean
/** 可以帶任意業務欄位 */
[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、AutoCompleteEmits 和上面 Props、Events 表一一對應。