CommandPalette 命令面板
集中搜尋頁面和操作命令。支援分組、關鍵詞、鍵盤導航和自訂結果;通常在應用版面配置中放置一個實例。
引入
import { HuiCommandPalette } from '@nscode/handy-ui'
import type {
CommandPaletteItem,
CommandPaletteProps,
CommandPaletteEmits,
CommandPaletteExpose
} from '@nscode/handy-ui'
示例
基礎用法
點擊按鈕或按 mod+k 打開。mod 在蘋果系統上是 ⌘,其他系統上是 Ctrl。↑、↓ 選擇,Enter執行,Esc 關閉。select 先通知業務,再呼叫命令自己的 action;預設先關閉、歸還焦點,下一幀才執行。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCommandPalette, HuiKbd, HuiMessage, HuiSpace } from '@nscode/handy-ui'
import type { CommandPaletteItem } from '@nscode/handy-ui'
const palette = ref<InstanceType<typeof HuiCommandPalette>>()
const selected = ref('尚未選擇')
const items: CommandPaletteItem[] = [
{
id: 'users',
label: '使用者管理',
group: '頁面',
icon: 'user',
action: () => HuiMessage.success('打開使用者管理')
},
{
id: 'settings',
label: '系統設定',
group: '頁面',
icon: 'search',
action: () => HuiMessage.success('打開系統設定')
},
{
id: 'save',
label: '保存目前修改',
group: '操作',
icon: 'check',
action: () => HuiMessage.success('已保存')
}
]
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace align="center"
><HuiButton @click="palette?.open()">打開命令面板</HuiButton><span>或按</span
><HuiKbd keys="mod+k"
/></HuiSpace>
<span>最近選擇:{{ selected }}</span>
<HuiCommandPalette ref="palette" :items="items" @select="selected = $event.label" />
</HuiSpace>
</template>
拼音和別名
搜尋按空白分詞,每個詞都要出現在 label 或某個 keywords 中,不區分大小寫。拼音和首字母不內建,填入關鍵詞即可。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCommandPalette, HuiMessage } from '@nscode/handy-ui'
const palette = ref<InstanceType<typeof HuiCommandPalette>>()
const items = [
{ label: '使用者管理', keywords: ['yonghu', 'yh', 'users'] },
{ label: '角色管理', keywords: ['juese', 'js', 'roles'] },
{ label: '系統設定', keywords: ['xitong', 'xt', 'settings'] }
]
</script>
<template>
<HuiButton @click="palette?.open()">試著搜尋 yh、juese 或 settings</HuiButton>
<HuiCommandPalette
ref="palette"
:items="items"
:hotkey="false"
@select="HuiMessage.success($event.label)"
/>
</template>
說明、快捷鍵和禁用項
description 只顯示,不參與搜尋。shortcut 只展示快捷鍵,不會註冊監聽。禁用項保留在結果中,滑鼠和方向鍵均不能選中執行。僅切換其他項目的禁用狀態時保留目前選取項;目前項被禁用或結果的 key 順序改變時,才重置到第一個可用項。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCommandPalette, HuiMessage } from '@nscode/handy-ui'
const palette = ref<InstanceType<typeof HuiCommandPalette>>()
const items = [
{ label: '保存', description: '保存目前編輯內容', shortcut: 'mod+s', icon: 'check' },
{ label: '搜尋', description: '在目前頁面查找', shortcut: 'mod+f', icon: 'search' },
{ label: '歸檔', description: '目前記錄沒有歸檔權限', disabled: true }
]
</script>
<template>
<HuiButton @click="palette?.open()">查看命令資訊</HuiButton>
<HuiCommandPalette
ref="palette"
:items="items"
:hotkey="false"
@select="HuiMessage.success($event.label)"
/>
</template>
自訂快捷鍵
Ctrl、⌘、Alt 的組合鍵在輸入框裡也能打開面板;/ 這種普通字元在輸入框裡保留輸入行為。傳 false 可只使用按鈕或實例方法打開。
<script setup lang="ts">
import { ref } from 'vue'
import {
HuiButton,
HuiCommandPalette,
HuiInput,
HuiKbd,
HuiMessage,
HuiSpace
} from '@nscode/handy-ui'
const print = ref<InstanceType<typeof HuiCommandPalette>>()
const slash = ref<InstanceType<typeof HuiCommandPalette>>()
const text = ref('')
const items = [{ label: '輸出預覽' }, { label: '導出文件' }]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap align="center">
<HuiButton @click="print?.open()">組合鍵面板</HuiButton><HuiKbd keys="mod+p" />
<HuiButton @click="slash?.open()">單鍵面板</HuiButton><HuiKbd keys="/" />
</HuiSpace>
<HuiInput v-model="text" placeholder="這裡可以輸入 /,mod+p 仍能打開面板" />
<HuiCommandPalette
ref="print"
:items="items"
hotkey="mod+p"
@select="HuiMessage.success($event.label)"
/>
<HuiCommandPalette
ref="slash"
:items="items"
hotkey="/"
@select="HuiMessage.success($event.label)"
/>
</HuiSpace>
</template>
遠端搜尋
用 v-model:query 接管查詢,結果回填 items。filter 返回 true 保留伺服端順序,不再重複本地篩選。輸入防抖300ms後發起模擬請求,頁面顯示請求次數;新輸入立即使舊請求失效。loading 期間隱藏舊命令,不顯示空結果,滑鼠和Enter均不能執行。
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { HuiButton, HuiCommandPalette, HuiMessage } from '@nscode/handy-ui'
import type { CommandPaletteItem } from '@nscode/handy-ui'
const palette = ref<InstanceType<typeof HuiCommandPalette>>()
const query = ref('')
const source = [{ label: '華東訂單' }, { label: '華南訂單' }, { label: '華北訂單' }]
const items = ref<CommandPaletteItem[]>(source)
const loading = ref(false)
const requests = ref(0)
let timer: ReturnType<typeof setTimeout> | undefined
let revision = 0
const search = (value: string) => {
const current = ++revision
clearTimeout(timer)
loading.value = true
timer = setTimeout(async () => {
requests.value++
const result = await new Promise<CommandPaletteItem[]>((resolve) => {
setTimeout(() => resolve(source.filter((item) => item.label.includes(value.trim()))), 500)
})
if (current !== revision) return
items.value = result
loading.value = false
}, 300)
}
onBeforeUnmount(() => {
revision++
clearTimeout(timer)
})
</script>
<template>
<HuiButton @click="palette?.open()">搜尋訂單</HuiButton>
<HuiCommandPalette
ref="palette"
v-model:query="query"
:items="items"
:loading="loading"
:hotkey="false"
:filter="() => true"
@update:query="search"
@select="HuiMessage.success($event.label)"
>
<template #loading="{ query }">正在查詢“{{ query }}”…</template>
<template #footer
>請求次數:{{ requests }};{{ loading ? '正在查詢…' : `已回傳 ${items.length} 筆` }}</template
>
</HuiCommandPalette>
</template>
自訂清單、空結果和頁腳
item 插槽獲得 item、active、query;互動和 ARIA 仍由外層選項負責。empty 插槽獲得目前查詢。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiAvatar, HuiButton, HuiCommandPalette, HuiMessage, HuiSpace } from '@nscode/handy-ui'
const palette = ref<InstanceType<typeof HuiCommandPalette>>()
const items = [
{ label: '張敏', description: 'zhang@example.com', keywords: ['zhang', 'zm'] },
{ label: '李華', description: 'li@example.com', keywords: ['li', 'lh'] }
]
</script>
<template>
<HuiButton @click="palette?.open()">搜尋聯絡人</HuiButton>
<HuiCommandPalette
ref="palette"
:items="items"
:hotkey="false"
@select="HuiMessage.success(`選擇了${$event.label}`)"
>
<template #item="{ item, active, query }">
<HuiAvatar :label="item.label.slice(0, 1)" size="small" />
<HuiSpace direction="vertical" :size="0"
><strong>{{ item.label }}</strong
><span>{{ item.description }}</span></HuiSpace
>
<span v-if="active">{{ query ? `匹配:${query}` : '目前選中' }}</span>
</template>
<template #empty="{ query }">沒有找到“{{ query }}”,請換一個名稱。</template>
<template #footer
><HuiButton size="small" @click="palette?.close()">關閉聯絡人搜尋</HuiButton></template
>
</HuiCommandPalette>
</template>
受控狀態、條數和選擇後保留
visible、query 按屬性是否傳入判斷受控,顯式 undefined 分別顯示關閉和空文字;僅監聽更新事件不會變成受控。受控操作只請求更新,父元件可以接受、正規化或拒絕;移除屬性恢復此前內部值。受控面板選擇時會請求關閉,父元件回填 false 後才執行命令。如果下一幀仍未接受關閉,本次執行取消,使用者可以繼續選擇;後來單獨關閉不會補執行舊命令。closeOnSelect=false 則保留面板並立即執行。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCommandPalette, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
const visible = ref(false)
const query = ref('')
const closeOnSelect = ref(false)
const selected = ref('尚未選擇')
const items = Array.from({ length: 12 }, (_, index) => ({
id: index,
label: `命令 ${index + 1}`
}))
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace align="center"><HuiSwitch v-model="closeOnSelect" /><span>選擇後關閉</span></HuiSpace>
<HuiButton @click="visible = true">打開 420px、最多 5 條的面板</HuiButton>
<span>最近選擇:{{ selected }};目前查詢:{{ query }}</span>
<HuiCommandPalette
v-model:visible="visible"
v-model:query="query"
:items="items"
:hotkey="false"
:limit="5"
:width="420"
:close-on-select="closeOnSelect"
@select="selected = $event.label"
/>
</HuiSpace>
</template>
自訂評分、文案與方法
預設按名稱和關鍵詞評分:開頭匹配優於詞首,詞首優於中間;名稱權重是關鍵詞的兩倍。自訂 filter 可回傳正數調整順序,false 或 0 排除。空查詢保留原始順序,不呼叫 filter。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCommandPalette, HuiMessage, HuiSpace } from '@nscode/handy-ui'
import type { CommandPaletteItem } from '@nscode/handy-ui'
const palette = ref<InstanceType<typeof HuiCommandPalette>>()
const state = ref('關閉')
const items = [{ label: '查看報表' }, { label: '建立報表' }, { label: '建立訂單' }]
const filter = (item: CommandPaletteItem, query: string) => {
if (!item.label.includes(query)) return false
return item.label.startsWith('建立') ? 10 : 1
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace align="center"
><HuiButton @click="palette?.open()">open()</HuiButton
><HuiButton @click="palette?.toggle()">toggle()</HuiButton></HuiSpace
>
<span>面板狀態:{{ state }}</span>
<HuiCommandPalette
ref="palette"
:items="items"
:hotkey="false"
width="70vw"
:filter="filter"
placeholder="搜尋報表或建立"
empty-text="換一個關鍵詞試試"
@update:visible="state = $event ? '打開' : '關閉'"
@select="HuiMessage.success($event.label)"
>
<template #footer
><HuiButton size="small" @click="palette?.close()">close()</HuiButton></template
>
</HuiCommandPalette>
</HuiSpace>
</template>
父元件每次呈現重建命令
createItems() 每次父元件呈現都回傳新物件。唯一 id、順序和禁用狀態不變時,活動項保持;關閉後按 key 查找最新物件,select 和 action 都使用該物件。本例關閉請求會更新版本,可核對執行結果。先按 ↓ 選擇第二項,再點頁腳刷新,活動項不會跳回第一項。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiCommandPalette, HuiSpace } from '@nscode/handy-ui'
import type { CommandPaletteItem } from '@nscode/handy-ui'
const visible = ref(false)
const version = ref(1)
const selected = ref('尚未選擇')
const executed = ref('尚未執行')
const createItems = (): CommandPaletteItem[] => {
const currentVersion = version.value
return [
{ id: 'report', label: '查看報表' },
{ id: 'settings', label: '保存設定' }
].map((item) => ({
...item,
description: `版本 ${currentVersion}`,
action: () => {
executed.value = `${item.label},版本 ${currentVersion}`
}
}))
}
const updateVisible = (value: boolean) => {
visible.value = value
if (!value) version.value++
}
const onSelect = (item: CommandPaletteItem) => {
selected.value = `${item.label},${item.description}`
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiButton @click="visible = true">打開動態命令</HuiButton>
<span>目前版本:{{ version }};select:{{ selected }};action:{{ executed }}</span>
<HuiCommandPalette
:visible="visible"
:items="createItems()"
:hotkey="false"
@update:visible="updateVisible"
@select="onSelect"
>
<template #footer>
<HuiButton size="small" @mousedown.prevent @click="version++"
>刷新命令,保留活動項</HuiButton
>
</template>
</HuiCommandPalette>
</HuiSpace>
</template>
Props
| 屬性 | 說明 | 類型 | 預設值 |
|---|---|---|---|
| items | 命令清單 | CommandPaletteItem[] | 必填 |
| visible | 是否打開,支援 v-model:visible;未傳時內部管理 | boolean | — |
| hotkey | 打開/關閉的快捷鍵;false 不註冊 | string | false | 'mod+k' |
| query | 搜尋文字,支援 v-model:query;未傳時內部管理 | string | — |
| placeholder | 輸入框提示文字;空字串有效 | string | 語言包 |
| emptyText | 空結果文字;空字串有效 | string | 語言包 |
| loading | 搜尋中;隱藏舊結果和空態,暫停執行命令 | boolean | false |
| limit | 最多顯示條數;0 不顯示結果,非有限數字回退 100 | number | 100 |
| closeOnSelect | 選中後關閉;false 時立即執行並保留面板 | boolean | true |
| filter | 自訂匹配和評分;空查詢時不呼叫 | (item, query) => number | boolean | — |
| width | 面板寬度,數字按 px | number | string | 640 |
Events
| 事件 | 說明 | 參數 |
|---|---|---|
| update:visible | 請求打開或關閉 | visible: boolean |
| update:query | 輸入文字變化 | query: string |
| select | 命令被選中,先於其 action 執行 | item: CommandPaletteItem |
Slots
| 插槽 | 說明 | 參數 |
|---|---|---|
| item | 自訂結果內容 | { item, active, query } |
| empty | 沒有結果時的內容 | { query } |
| loading | 搜尋中內容;預設取語言包的載入文字 | { query } |
| footer | 替換底部鍵盤提示 | — |
方法
| 方法 | 說明 | 參數 |
|---|---|---|
| open | 請求打開面板 | — |
| close | 請求關閉面板 | — |
| toggle | 請求切換打開狀態 | — |
類型
interface CommandPaletteItem {
id?: string | number
label: string
description?: string
group?: string
icon?: string
keywords?: string[]
shortcut?: string
disabled?: boolean
action?: () => void
}
interface CommandPaletteExpose {
open: () => void
close: () => void
toggle: () => void
}