Debounce Input Directive
Write a custom directive to debounce input field events to limit the rate of event firing during typing, useful for search inputs or real-time validation.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
This is a generic debounce function that can be used to wrap any function you want to debounce. It accepts a function, a wait time, and a boolean to indicate if it should run at the start of the wait period (`immediate`).
Vue.directive('debounce', {
inserted: function(el, binding) {
if (typeof binding.value !== 'function') {
throw new Error('The argument for v-debounce must be a function');
}
var wait = binding.arg || 300;
el.oninput = debounce(function(event) {
binding.value(event.target.value);
}, wait);
},
unbind: function(el) {
el.oninput = null;
}
});
This creates a Vue directive called `debounce`. It uses the debounce function previously defined to debounce input events on the element it is applied to. The value passed to the directive should be a function which will be called with the input's value. The argument is the number of milliseconds to wait; if not provided, it defaults to 300ms.
<input v-debounce:400="myDebouncedFunction" />
Example usage of the `v-debounce` directive in a Vue template. It applies a 400ms debounce to the input element's 'input' event, calling `myDebouncedFunction` with the input's value when triggered.