首页 > 解决方案 > 使用 Vue 类组件语法对方法进行去抖动/节流

问题描述

我正在开发一个组件,该组件在搜索栏中的文本发生更改时查询外部 API,并且我正在尝试对该查询进行去抖动,以便它只能每 2 秒执行一次。我正在尝试使用 lodash 的debounce功能来做到这一点,并且发现了多个博客文章和关于将它与 Vue 组件一起使用的 SO 问题,但是事情很复杂,因为我使用的是 Typescript 和 Vue 类组件语法(https://class-组件.vuejs.org /)。老实说,我对这两个都很陌生。

我发现一篇博客文章概述了如何使用基于对象的 Vue 组件语法来做到这一点,但它不适用于类组件语法。基于对象的语法允许您将方法包装在 a_.debounce中,如下所示:

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

有没有办法用 Vue 类组件语法做类似的事情?

以下是我的代码的相关部分(没有任何反跳尝试):

<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>

标签: typescriptvue.jslodashvue-class-components

解决方案


这里已经讨论过了。

基本上,您需要定义基本函数(就像您对 所做的那样doSearch),然后定义新的去抖动函数:

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

现在你只需要打电话doSearchDebounced而不是doSearch


推荐阅读