JAVASCRIPT
Creating a Debounce Composable for Input Fields in Vue 3
Develop a custom Vue 3 Composition API composable to debounce user input, improving performance for search fields and preventing excessive API calls or computations during typing.
// src/composables/useDebouncedInput.js
import { ref, watch } from 'vue';
export function useDebouncedInput(value, delay = 500) {
let timeout;
const inputValue = ref(value.value); // Internal state for the input
const debouncedRef = ref(value.value); // The debounced output ref
watch(inputValue, (newVal) => {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
debouncedRef.value = newVal;
}, delay);
});
// Update inputValue if the original 'value' changes externally
watch(value, (newVal) => {
inputValue.value = newVal;
}, { immediate: true });
return { inputValue, debouncedRef };
}
// src/components/SearchInput.vue
<template>
<input type="text" v-model="searchQuery.inputValue" placeholder="Type to search..." />
<p>Searching for: {{ searchQuery.debouncedRef }}</p>
<p>API Call would trigger with: {{ searchQuery.debouncedRef }}</p>
</template>
<script setup>
import { ref, watch } from 'vue';
import { useDebouncedInput } from '../composables/useDebouncedInput';
const searchTerm = ref('');
const searchQuery = useDebouncedInput(searchTerm, 700);
// Example of watching the debounced value to trigger an API call
watch(searchQuery.debouncedRef, (newVal) => {
if (newVal) {
console.log(`Performing API search for: ${newVal}`);
// Here you would typically make an API call
}
});
</script>
How it works: This snippet provides a `useDebouncedInput` composable for Vue 3 that helps debounce user input from an `input` field. It takes a `ref` and a `delay` as arguments. As the user types, `inputValue` updates immediately, but `debouncedRef` (the value intended for operations like API calls) only updates after the specified `delay` has passed since the last input. This prevents performance issues from frequent updates or excessive network requests while typing.