Ready

  • 注意options.ready的类型必须是Ref<boolean>
  • 通过设置 options.ready,可以控制请求是否发出。当其值为 false 时,请求永远都不会发出。

其具体行为如下:

  1. manual=false 自动请求模式时,每次 readyfalse 变为 true 时,都会自动发起请求,会带上参数 options.defaultParams
  2. manual=true 手动请求模式时,只要 ready=false,则通过 run/runAsync 触发的请求都不会执行。

自动模式

以下示例演示了自动模式下 ready 的行为。每次 readyfalse 变为 true 时,都会重新发起请求。

- - ready:false

data:
点击查看代码
<script setup>
import { mockFetch } from "@/api";
import { useRequest } from "ahooks-for-vue";
import { ref, watch } from "vue";
const ready = ref(false);

const { loading, data, run } = useRequest(mockFetch, {
  ready,
});

const set = (v) => {
  ready.value = v;
};
</script>
<template>
  <div>
    <button @click="() => set(true)">set ready true</button>
    -
    <button @click="() => set(false)">set ready false</button>
    - ready:{{ ready }} <br /><br />
    data: {{ loading ? "loading..." : data }}
  </div>
</template>
<style></style>

手动模式

以下示例演示了手动模式下 ready 的行为。只有当 ready 等于 true 时,run 才会执行。

- - ready:false

data:

点击查看代码
<script setup>
import { mockFetch } from "@/api";
import { useRequest } from "ahooks-for-vue";
import { ref, watch } from "vue";
const ready = ref(false);

const { loading, data, run } = useRequest(mockFetch, {
  ready,
  manual: true,
});

const set = (v) => {
  ready.value = v;
};
</script>
<template>
  <div>
    <button @click="() => set(true)">set ready true</button>
    -
    <button @click="() => set(false)">set ready false</button>
    - ready:{{ ready }} <br /><br />
    data: {{ loading ? "loading..." : data }} <br /><br />
    <button @click="() => run()">请求数据</button>
  </div>
</template>
<style></style>

API

Options

参数说明类型默认值
ready当前请求是否准备好了Ref<boolean>Ref<true>
Last Updated:
Contributors: 郑磊