add search bar to search page and improve searhc on input hcange

This commit is contained in:
Ruidy 2024-12-17 21:12:46 +01:00
parent b19cb02763
commit 5bd9f2c382
No known key found for this signature in database
GPG key ID: E00F51288CB857CC
3 changed files with 24 additions and 35 deletions

View file

@ -11,31 +11,6 @@ const handleRandomClick = async () => {
}
await execute();
};
const debouncedSearch = useDebounceFn(async (query: string) => {
if (searchQuery.value.trim()) {
router.push({
path: "/search",
query: { q: query.trim() },
});
}
}, 500);
const handleSubmit = () => {
if (searchQuery.value.trim()) {
router.push({
path: "/search",
query: { q: searchQuery.value.trim() },
});
}
};
if (route.path === "/search") {
// Watch for changes in searchQuery
watch(searchQuery, (newQuery) => {
debouncedSearch(newQuery);
});
}
</script>
<template>
@ -78,11 +53,7 @@ if (route.path === "/search") {
<icon name="uil:search" class="w-6 h-6" />
</nuxt-link>
<!-- Search bar for larger screens -->
<recipe-search
v-model="searchQuery"
@search="handleSubmit"
class="hidden sm:flex"
/>
<recipe-search v-model="searchQuery" class="hidden sm:flex" />
<button class="btn btn-primary" @click="handleRandomClick">Random</button>
</div>
</nav>

View file

@ -9,19 +9,36 @@
placeholder="Search recipes..."
@focus="isFocused = true"
@blur="isFocused = false"
@keydown.enter="$emit('search')"
>
<kbd class="kbd kbd-sm" :class="{ 'opacity-50': !isFocused }"></kbd>
<kbd class="kbd kbd-sm" :class="{ 'opacity-50': !isFocused }">K</kbd>
<kbd
class="hidden md:inline-block kbd kbd-sm"
:class="{ 'opacity-50': !isFocused }"
>
</kbd>
<kbd
class="hidden md:inline-block kbd kbd-sm"
:class="{ 'opacity-50': !isFocused }"
>
K
</kbd>
</label>
</template>
<script setup lang="ts">
defineEmits(["search"]);
const model = defineModel<string>();
const isFocused = ref(false);
// Debounced navigation
const debouncedSearch = useDebounceFn((query: string) => {
navigateTo(`/search?q=${encodeURIComponent(query || "")}`);
}, 200);
// Watch for changes in model
watch(model, (newQuery) => {
debouncedSearch(newQuery || "");
});
onMounted(() => {
const handleKeydown = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === "k") {

View file

@ -38,6 +38,7 @@ watch(searchQuery, async (newQuery) => {
v-else-if="searchResults.length > 0"
class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 my-8"
>
<recipe-search class="md:hidden mb-6" :initial-query="searchQuery" />
<div
v-for="recipe in searchResults"
:key="recipe.id"