使用 Vue 类组件语法对方法进行去抖动/限制

pcr*_*non 5 typescript lodash vue.js vue-class-components

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

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

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

有没有办法用 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>
Run Code Online (Sandbox Code Playgroud)

gba*_*zzi 5

这里已经讨论过了。

基本上,您需要定义基本函数(就像使用 一样doSearch),然后定义新的去抖函数:

public doSearchDebounced = _.debounce(this.doSearch, 2000)
Run Code Online (Sandbox Code Playgroud)

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