Blog>
Snippets

Debounced Watcher with Vue

Implement a debounced watcher in Vue.js 3 that postpones executing the effect until after the value has stopped changing for a specified period.
import { ref, watch } from 'vue';
import _ from 'lodash'; // Import the lodash library for the debounce function

export default {
  setup() {
    // Assume we are debouncing a search input
    const searchQuery = ref('');

    // Watcher with debounce
    const debouncedSearch = _.debounce((newValue) => {
      console.log(`Search query: ${newValue}`); // Replace with your search logic
    }, 500); // 500ms debounce time

    watch(searchQuery, (newValue, oldValue) => {
      debouncedSearch(newValue);
    });

    return {
      searchQuery
    };
  },
};
This code creates a Vue component with a `searchQuery` reactive state using Vue 3's Composition API. It then creates a `debouncedSearch` function using lodash's `debounce` function, set to wait for 500 milliseconds after the last input event before invoking the provided function. A watcher is set up on the `searchQuery` state that calls the debounced function whenever `searchQuery` changes. Replace `console.log` with the actual search logic to be performed after the debounce period.