Ben Lin
2024-06-23 f1d47feeee1ddb5751847b71f789f2c3b822ec32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { defineComponent, ref, unref } from 'vue';
import { Card, Typography, Button, Space } from 'ant-design-vue';
import { imitateApi } from './mock-api';
import { useRequest } from '@vben/hooks';
import { PageWrapper } from '@/components/Page';
 
const Demo1 = defineComponent({
  setup() {
    const ready = ref(false);
    const toggle = (bool?: boolean) => {
      ready.value = bool ?? !ready.value;
    };
    const { data, loading } = useRequest(imitateApi, { ready });
 
    return () => (
      <Card title="自动模式">
        <Typography>
          <Typography.Paragraph>
            以下示例演示了自动模式下
            <Typography.Text type="danger"> ready </Typography.Text> 的行为。每次
            <Typography.Text type="danger"> ready </Typography.Text> 从 false 变为 true
            时,都会重新发起请求。
          </Typography.Paragraph>
        </Typography>
 
        <div>
          <Space>
            <div>Ready: {JSON.stringify(unref(ready))}</div>
            <Button onClick={() => toggle()}>Toggle Ready</Button>
          </Space>
          <div>Username: {loading.value ? 'Loading' : unref(data)}</div>
        </div>
      </Card>
    );
  },
});
 
const Demo2 = defineComponent({
  setup() {
    const ready = ref(false);
    const toggle = (bool?: boolean) => {
      ready.value = bool ?? !ready.value;
    };
    const { data, loading, run } = useRequest(imitateApi, { manual: true, ready });
 
    return () => (
      <Card title="手动模式" class="mt-2">
        <Typography>
          <Typography.Paragraph>
            以下示例演示了手动模式下
            <Typography.Text type="danger"> ready </Typography.Text>
            的行为。只有当
            <Typography.Text type="danger"> ready </Typography.Text>
            等于 true 时,run 才会执行。
          </Typography.Paragraph>
        </Typography>
 
        <div>
          <Space>
            <div>Ready: {JSON.stringify(unref(ready))}</div>
            <Button onClick={() => toggle()}>Toggle Ready</Button>
          </Space>
          <div class="mt-2">
            <Space>
              <div>Username: {loading.value ? 'Loading' : unref(data)}</div>
              <Button type="primary" disabled={!ready.value} onClick={() => run()}>
                Run
              </Button>
            </Space>
          </div>
        </div>
      </Card>
    );
  },
});
 
export default defineComponent({
  setup() {
    return () => (
      <PageWrapper>
        <Demo1 />
        <Demo2 />
      </PageWrapper>
    );
  },
});