CommandPalette 命令面板
集中搜索页面和操作命令。支持分组、关键词、键盘导航和自定义结果;通常在应用布局中放置一个实例。
引入
import { HuiCommandPalette } from '@nscode/handy-ui'
import type {
CommandPaletteItem,
CommandPaletteProps,
CommandPaletteEmits,
CommandPaletteExpose
} from '@nscode/handy-ui'
示例
基础用法
点击按钮或按 mod+k 打开。mod 在苹果系统上是 ⌘,其他系统上是 Ctrl。↑、↓ 选择,回车执行,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 期间隐藏旧命令,不显示空结果,鼠标和回车均不能执行。
<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
}