Vue.js Snippets – Make API Request on User Input
Some applications like Gmail and Facebook have a search feature where as a user enters some input, the input is sent to the server and the results are used to provide the user with results closer to what the user is looking for.
To implement this behaviour in Vue, we use a library called debounce
that allows us to set a delay on the input field. The reason for this is so we only call our API when some time has passed since the user entered some input.
<template>
<div>
<input @input="searchInput" type="text">
</div>
</template>
<script>
import { debounce } from 'debounce'
export default {
methods: {
searchInput: debounce(function (e) {
// make API call here
}, 800)
}
}
</script>
Install debounce like so:
npm install --save debounce # for npm users
yarn add debounce # for yarn users
We listen for the input
event (called when there’s a new input) on the input field and bind it to searchInput
method. In the script section, we wrap searchInput
with debounce()
. debounce()
takes 2 parameters: a function that we want to run after the specified time has elapsed and the time duration to wait before running the function, in this case 800 milliseconds. We can make our API call inside the function and populate the application as needed.
Use Cases
- Book library
- Ecommerce store