perf: 全局搜索框打开后自动聚焦输入框 (#4006)

pull/48/MERGE
苗大 2024-08-02 21:56:47 +08:00 committed by GitHub
parent 8313be8e08
commit e544119aa3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 9 additions and 1 deletions

View File

@ -1,7 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import type { MenuRecordRaw } from '@vben/types'; import type { MenuRecordRaw } from '@vben/types';
import { onMounted, onUnmounted, ref, watch } from 'vue'; import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { import {
ArrowDown, ArrowDown,
@ -40,6 +40,7 @@ const props = withDefaults(
const [open, toggleOpen] = useToggle(); const [open, toggleOpen] = useToggle();
const keyword = ref(''); const keyword = ref('');
const searchInputRef = ref<HTMLInputElement>();
function handleClose() { function handleClose() {
open.value = false; open.value = false;
@ -54,6 +55,12 @@ whenever(cmd, () => {
} }
}); });
whenever(open, () => {
nextTick(() => {
searchInputRef.value?.focus();
});
});
const preventDefaultBrowserSearchHotKey = (event: KeyboardEvent) => { const preventDefaultBrowserSearchHotKey = (event: KeyboardEvent) => {
if (event.key.toLowerCase() === 'k' && (event.metaKey || event.ctrlKey)) { if (event.key.toLowerCase() === 'k' && (event.metaKey || event.ctrlKey)) {
event.preventDefault(); event.preventDefault();
@ -115,6 +122,7 @@ onMounted(() => {
> >
<Search class="text-muted-foreground size-4" /> <Search class="text-muted-foreground size-4" />
<input <input
ref="searchInputRef"
v-model="keyword" v-model="keyword"
:placeholder="$t('widgets.search.searchNavigate')" :placeholder="$t('widgets.search.searchNavigate')"
class="ring-none placeholder:text-muted-foreground w-[80%] rounded-md border border-none bg-transparent p-2 pl-0 text-sm outline-none ring-0 ring-offset-transparent focus-visible:ring-transparent" class="ring-none placeholder:text-muted-foreground w-[80%] rounded-md border border-none bg-transparent p-2 pl-0 text-sm outline-none ring-0 ring-offset-transparent focus-visible:ring-transparent"