Debouncing State Updates in Vue 3
Illustrate how to implement debouncing to batch or delay state updates in Vue 3, which can improve performance for scenarios like user input handling.
import { ref } from 'vue';
import _ from 'lodash'; // Import lodash for debouncing
export default {
setup() {
const searchText = ref(''); // Reactive state for search text
// Debounced function to call on input
// _.debounce(method, wait time in ms)
const updateQuery = _.debounce((newQuery) => {
searchText.value = newQuery; // Update the reactive state
}, 500); // Debounce for 500 ms
return { searchText, updateQuery };
}
};
This code snippet sets up a Vue 3 component with a debounced input handler using lodash. The `searchText` is a reactive state variable that holds the value of a search input. The `updateQuery` function is debounced, meaning it will only invoke the actual update of `searchText` after 500 milliseconds of inactivity, reducing the number of updates during rapid input changes.
<template>
<input type="text" @input="updateQuery($event.target.value)" />
<!-- This input will call the debounced function on each keystroke, delaying the update -->
</template>
<script setup>
// Import the script from above
</script>
This code snippet is the template part of the Vue component. It includes an input element that triggers the debounced `updateQuery` function upon each keystroke. Instead of immediately updating the state, it waits for 500 milliseconds of no input before committing the state change.