【发布时间】:2020-03-14 20:00:14
【问题描述】:
我正在开发一个组件,该组件会在搜索栏中的文本发生更改时查询外部 API,并且我正在尝试消除该查询的抖动,使其只能每 2 秒执行一次。我正在尝试使用 lodash 的 debounce 函数来做到这一点,并且发现了多个博客文章和关于将它与 Vue 组件一起使用的 SO 问题,但事情很复杂,因为我使用的是 Typescript 和 Vue 类组件语法 (https://class-component.vuejs.org/ )。老实说,我对这两个都很陌生。
我找到了a blog post outlining how to do this with object-based Vue component syntax,但它不适用于类组件语法。基于对象的语法允许您将方法包装在 _.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>
【问题讨论】:
标签: typescript vue.js lodash vue-class-components