节流

通过设置 options.throttleWait,进入节流模式,此时如果频繁触发 run 或者 runAsync,则会以节流策略进行请求。

const { data, run } = useRequest(getUsername, {
  throttleWait: 300,
  manual: true,
});

如上示例代码,频繁触发 run,只会每隔 300ms 执行一次。

你可以在下面 input 框中快速输入文本,体验效果


data:
点击查看代码
<script setup>
import { mockFetchFast } from "@/api";
import { useRequest } from "ahooks-for-vue";

const { loading, data, run } = useRequest(mockFetchFast, {
  throttleWait: 2000,
  manual: true,
  // throttleTrailing: false,
});
</script>
<template>
  <div>
    <input type="text" @input="run" />
    <br />
    data:{{ loading ? "loading..." : data }}
  </div>
</template>
<style></style>

API Options

throttle 所有参数用法和效果同 lodash.throttleopen in new window

参数说明类型默认值
throttleWait节流等待时间, 单位为毫秒,设置后,进入节流模式number-
throttleLeading在节流开始前执行调用booleantrue
throttleTrailing在节流结束后执行调用booleantrue

备注

  • options.throttleWaitoptions.throttleLeadingoptions.throttleTrailing 支持动态变化
  • runAsync 在真正执行时,会返回 Promise。在未被执行时,不会有任何返回。
  • cancel 可以中止正在等待执行的函数。
Last Updated:
Contributors: 郑磊