Files
heroui-vue/apps/docs/demos/search-field-with-keyboard-shortcut.vue
T
2026-10-22 08:46:02 +08:00

59 lines
1.6 KiB
Vue

<script setup lang="ts">
import {
SearchFieldClearButton,
SearchFieldSearchIcon,
SearchFieldGroup,
SearchFieldInput,
SearchField,
Label,
Description,
KbdAbbr,
KbdContent,
Kbd,
} from "@heroui-vue/components";
import { onBeforeUnmount, onMounted, ref } from "vue";
const input = ref<{ focus: () => void; element?: HTMLInputElement }>();
const value = ref("");
function keydown(event: KeyboardEvent) {
if (
event.shiftKey &&
event.key === "S" &&
!event.metaKey &&
!event.ctrlKey &&
!event.altKey &&
!event.isComposing
) {
event.preventDefault();
input.value?.focus();
}
if (event.key === "Escape" && document.activeElement === input.value?.element)
input.value.element.blur();
}
onMounted(() => window.addEventListener("keydown", keydown));
onBeforeUnmount(() => window.removeEventListener("keydown", keydown));
</script>
<template>
<div class="flex flex-col gap-4">
<div>
<SearchField v-model="value" name="search">
<Label>搜索</Label>
<SearchFieldGroup>
<SearchFieldSearchIcon />
<SearchFieldInput ref="input" class="w-[280px]" placeholder="搜索…" />
<SearchFieldClearButton />
</SearchFieldGroup>
<Description>使用键盘快捷键快速聚焦此输入框</Description>
</SearchField>
</div>
<div class="text-default-500 flex items-center gap-2 text-sm">
<span>按</span>
<Kbd>
<KbdAbbr key-value="shift" />
<KbdContent>S</KbdContent>
</Kbd>
<span>聚焦搜索框</span>
</div>
</div>
</template>