SearchBar.vue 1.59 KB
<script lang="ts" setup>
import { useDebounceFn } from "@vueuse/core";
// #region --import--.
import { SearchIcon, XIcon } from "lucide-vue-next";
import { ref } from "vue";
// #endregion

// #region --Props--.
withDefaults(defineProps<{
  placeholder?: string;
}>(), {
  placeholder: "",
});
// #endregion

// #region --Emits--.
const emit = defineEmits<{
  eventSearch: [search: string];
  eventClearSearch: [];
}>();
// #endregion

// #region --Data/refs--.
const searchQuery = ref("");
// #endregion

// #region --Function--.
/**
 * Debounced function
 */
const handleSearchEvent = useDebounceFn(() => {
  emit("eventSearch", searchQuery.value);
}, 500);

function handleClearSearchEvent() {
  searchQuery.value = "";
  emit("eventClearSearch");
}
// #endregion
</script>

<template>
  <!-- Barre de recherche -->
  <section class="mb-8">
    <div class="relative max-w-xl mx-auto">
      <input
        v-model="searchQuery"
        :placeholder="placeholder"
        class="w-full px-4 py-3 bg-gray-800 rounded-full text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-primary"
        type="text"
        @input="handleSearchEvent"
      >
      <button
        v-if="searchQuery"
        class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-white"
        @click="handleClearSearchEvent"
      >
        <XIcon :size="20" />
      </button>
      <button
        v-else
        class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400"
      >
        <SearchIcon :size="20" />
      </button>
    </div>
  </section>
</template>

<style scoped></style>