Debouncing an input event listener #198
-
Hi everyone! I'm using petite-vue for a simple web app and I'm trying to implement debouncing on a search input's 'input' listener, eg: Because I'm using an external API, I only want the 'getSearchResults' function to run after 250ms, so if someone is typing in the search input, the function will not run on every keypress. I also don't want it to be sending multiple requests if it doesn't have to (eg. if the user types in 'cat', I don't want it to search for 'c', then 'ca', then 'cat'). The tutorials that I've found online (eg. Josh W Comeau, FreeCodeCamp) don't quite line up with petite-vue, because petite-vue uses I've seen that AlpineJS has a I've made a simple codepen here if anyone wants to experiment: Thanks :-) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I found that petite-vue's markdown example uses lodash's debounce function: I got this working in my codepen fairly easily, so this is an ok solution for now! Here's a code example for posterity: <h1>petite-vue - hypothetical search</h1>
<div v-scope>
<label>Search</label>
<input name="q" v-model="searchInput" @input="getSearchResults" />
<p v-if="searching">Searching...</p>
<div v-if="searchResults.length > 0">
<h2>Search results</h2>
<ul>
<li v-for="searchResult in searchResults">
{{searchResult}}
</li>
</ul>
</div>
</div>
<script src="https://unpkg.com/[email protected]/lodash.min.js"></script>
<script type="module">
async function getSearchResults() {
const searchQuery = this.searchInput;
console.log("fetching search results for query", searchQuery);
this.searching = true;
// return results after 2 seconds
const results = await new Promise((resolve) => {
setTimeout(function () {
resolve([1, 2, 3, 4, 5]);
}, 2000);
});
this.searchResults = results;
this.searching = false;
console.log("finished searching for query", searchQuery);
}
import { createApp } from "https://unpkg.com/petite-vue?module";
createApp({
searchResults: [],
searching: false,
searchInput: "",
// _ comes from the lodash script above
getSearchResults: _.debounce(getSearchResults, 250)
}).mount();
</script> |
Beta Was this translation helpful? Give feedback.
I found that petite-vue's markdown example uses lodash's debounce function:
https://github.com/vuejs/petite-vue/blob/71aefbf2d79852cdc3ccd63b7d3c79221f7c5fb4/examples/markdown.html
I got this working in my codepen fairly easily, so this is an ok solution for now!
Here's a code example for posterity: