在触发函数之前等待 x 秒以获得新的发射值

Wait x seconds for new emitted value before triggering a function

我有一个 child 组件发出一个值,在 parent 中,我每次发出该值时都执行 axios 调用。我的问题是,我只想在 x 毫秒(或秒)内触发 axios 调用 child 没有发出另一个值以减少我所做的调用量。

代码在这里:

<script>
import axios from "axios";

import DataTable from './DataTable.vue';

export default {
    name: 'Test',
    data() {
        return {
            gamertags: [],

            // Utils
            timeout: 500,
            delay: 500
        }
    },
    methods: {
        // API calls
        async getGamerTags(string='') {
            const path = `http://localhost:5000/gamertags?string=${string}`
            await axios.get(path)
                .then((res) => {
                    this.gamertags = res.data;
                })
                .catch((error) => {
                    console.error(error);
                });
        },

        // DataTable
        handleFilters(filters) {
            clearTimeout(this.timeout);
            this.timeout = setTimeout(this.getGamerTags(filters.find(o => o.field == "playerGamerTag").filter), this.delay);
        }
    }
    components: {
        DataTable
    }
};
</script>

<template>
    <DataTable
        @filters="handleFilters"
    />
</template>

提前致谢。

如果您也添加代码,会更好地理解问题和用例。 但据我所知,这是两种方式

  1. 如果您使用内部输入和基于触发的 @changed 事件,您可以添加 @change.lazy 这不会在每次更改时触发。
  2. 第二个解决方案是在 parent
  3. 中使用 setTimeout(function,delayInMs)

vuejs Docs link

你需要的是debouncing。这是一个例子:

var timeout, delay = 3000;

function func1() {
  clearTimeout(timeout);
  timeout = setTimeout(function(){
    alert("3000 ms inactivity");
  }, delay);
}
<input type="text" oninput="func1()">

发射时,直接调用func1(),如果3000毫秒后没有新的发射,将执行timeout中的函数。

只需将 handleFilters 函数更改为 :

handleFilters(filters) {
   clearTimeout(this.timeout);
   this.timeout = setTimeout(
      this.getGamerTags,
      this.delay,
      filters.find(o => o.field == "playerGamerTag").filter
   );
},

问题已解决