JAVASCRIPT
Debounce Input with Vue 3 Composition API for Search Fields
Efficiently debounce user input in Vue 3 search fields or textareas using `watch` and `ref` from the Composition API, reducing API calls and improving performance.
<template>
<div>
<input
type="text"
v-model="searchTerm"
placeholder="Type to search..."
class="search-input"
/>
<p>Searching for: {{ debouncedSearchTerm }}</p>
<p v-if="debouncedSearchTerm">
(Simulating API call for "{{ debouncedSearchTerm }}" after {{ debounceDelay }}ms)
</p>
</div>
</template>
<script setup>
import { ref, watch } from 'vue';
const searchTerm = ref('');
const debouncedSearchTerm = ref('');
const debounceDelay = 500; // milliseconds
let timeoutId = null;
watch(searchTerm, (newValue) => {
// Clear any existing timeout
if (timeoutId) {
clearTimeout(timeoutId);
}
// Set a new timeout
timeoutId = setTimeout(() => {
debouncedSearchTerm.value = newValue;
// Here you would typically trigger an API call or expensive computation
console.log('Debounced search term:', newValue);
}, debounceDelay);
});
</script>
<style scoped>
.search-input {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
width: 300px;
font-size: 16px;
}
</style>
How it works: This snippet demonstrates how to implement debouncing for an input field using the Vue 3 Composition API. When `searchTerm` changes, a `watch` effect is triggered. Instead of immediately updating `debouncedSearchTerm` or making an API call, it clears any previously set timeout and sets a new one. If `searchTerm` changes again before the `debounceDelay` elapses, the previous timeout is cancelled, and a new one is set. This ensures that the expensive operation (like an API call) only occurs after the user has paused typing for the specified delay, preventing excessive requests.