Categories
Vue Answers

How to implement debounce in Vue.js?

Spread the love

Sometimes, we want to implement debounce in Vue.js.

In this article, we’ll look at how to implement debounce in Vue.js.

How to implement debounce in Vue.js?

To implement debounce in Vue.js, we can use the Lodash debounce method.

To install it, we run

npm i lodash

Then we use it by writing

<template <input @input="debounceInput"></template>

<script>
import { debounce } from "lodash";
//...
export default {
  methods: {
    debounceInput: debounce(function (e) {
      this.$store.dispatch("updateInput", e.target.value);
    }, 1000),
  },
};
</script>

to set the debounceInput method to the debounced version of the method that calls this.$store.dispatch with the e.target.value input value.

We debounce the method by 1000 milliseconds by setting the 2nd argument of debounce to 1000.

Then we set the @input directive to debounceInput to run debounceInput when the input event is emitted.

Conclusion

To implement debounce in Vue.js, we can use the Lodash debounce method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *