Implementing a live search feature using debouncing in Vue.js involves using a combination of Vue.js reactivity for data binding and JavaScript's debounce function to limit the number of API requests triggered by user input. Below is a simple example demonstrating how to achieve this:
html<template>
<div>
<input type="text" v-model="searchTerm" @input="handleInput" placeholder="Search...">
<ul>
<li v-for="result in searchResults" :key="result.id">{{ result.name }}</li>
</ul>
</div>
</template>
<script>
import { debounce } from 'lodash'; // Import debounce function from lodash library
export default {
data() {
return {
searchTerm: '',
searchResults: []
};
},
methods: {
handleInput: debounce(function() {
// Perform API call with the debounced search term
this.fetchSearchResults();
}, 500), // Adjust debounce delay as needed
async fetchSearchResults() {
try {
// Make API request with this.searchTerm and update searchResults
const response = await fetch(`https://api.example.com/search?q=${this.searchTerm}`);
const data = await response.json();
this.searchResults = data.results;
} catch (error) {
console.error('Error fetching search results:', error);
}
}
}
};
</script>
<style scoped>
/* Add your CSS styles here */
</style>
In this example:
searchTerm
data property using v-model
.@input
event to trigger the handleInput
method every time the user types in the input field.handleInput
method is debounced using lodash's debounce
function. This ensures that the API call is only made after a short delay (500 milliseconds in this example) after the user stops typing, reducing the number of unnecessary API requests.fetchSearchResults
method, we make an asynchronous API call using fetch
and update the searchResults
data property with the fetched results.Ensure you have lodash library installed (npm install lodash
) and imported it as shown in the example. Adjust the API endpoint and debounce delay according to your requirements.