Search code examples
typescriptvue.jslodashvue-class-components

Debouncing/throttling a method using Vue Class Component Syntax


I'm working on a component which queries an external API when the text in a search bar changes, and I'm trying to debounce that query so it can only execute every 2 seconds. I'm trying to use lodash's debounce function to do that, and have found multiple blog posts and SO questions about using it with Vue components, but things are complicated because I am using Typescript and the Vue Class Component Syntax (https://class-component.vuejs.org/). And to be honest I'm quite new to both of those.

I found a blog post outlining how to do this with object-based Vue component syntax, but it doesn't apply to the Class Component Syntax. The object-based syntax allows you to wrap your methods inside a _.debounce, like this:

export default {
  methods: {
    throttledMethod: _.debounce(() => {
      console.log('I only get fired once every two seconds, max!')
    }, 2000)
  }
}

Is there a way to do something similar with the Vue Class Component syntax?

Here are the relevant sections of my code (without any attempts at debouncing):

<template>
  <input
    v-model="searchQuery"
    @keydown="doSearch"
  >
</template>

<script lang="ts">
import axios from 'axios';
import _ from 'lodash';
import { Component, Vue } from 'vue-property-decorator';

@Component
export default class FooSearch extends Vue {
  // data
  searchQuery = '';
  results = [];

  // methods
  async doSearch() {
    try {
      const response = await axios.get('https://api.example.org/search', {
        params: {
          query: this.searchQuery,
        }
      });

      this.results = response.data.results;
    } catch(error) {
      console.log('error');
      console.log(error);
    }
  }
</script>

Solution

  • It has been discussed here.

    Basically, you need to define your base function (like you did with doSearch) and then define the new debounced function:

    public doSearchDebounced = _.debounce(this.doSearch, 2000)
    

    Now yu simply need to call doSearchDebounced instead of doSearch