Ben Lin
2024-06-25 f73947395184fd635df3d74c1c4b2701d0c708c1
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import { defineComponent, onMounted, ref, unref } from 'vue';
import { Card, Spin, Typography, message, Input, 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 { data, error, loading } = useRequest(imitateApi);
 
    return () => (
      <Card title="默认用法">
        <Typography>
          <Typography.Paragraph>
            <Typography.Text type="danger">useRequest </Typography.Text>
            的第一个参数是一个异步函数,在组件初次加载时,会自动触发该函数执行。同时自动管理该异步函数的
            <Typography.Text code>loading</Typography.Text>
            <Typography.Text code>data</Typography.Text>
            <Typography.Text code>error</Typography.Text>
            等状态。
          </Typography.Paragraph>
          <Typography.Text code>
            {`const { data, error, loading } = useRequest(imitateApi);`}
          </Typography.Text>
        </Typography>
 
        {/* 基础案例 */}
        <Spin spinning={loading.value}>
          <div class="mt-4">{error.value ? 'failed to load' : `Username: ${data.value}`}</div>
        </Spin>
      </Card>
    );
  },
});
 
const Demo2 = defineComponent({
  setup() {
    const search = ref('');
    const setSearch = (value: string) => {
      search.value = value;
    };
 
    const { loading, run } = useRequest(imitateApi, {
      manual: true,
      onSuccess: (result, params) => {
        if (result) {
          setSearch('');
          message.success(`The username was changed to "${params[0]}" !`);
        }
      },
    });
 
    return () => (
      <Card title="手动触发" class="mt-2">
        <Typography>
          <Typography.Paragraph>
            如果设置了
            <Typography.Text type="danger"> options.manual = true </Typography.Text>
            ,则 useRequest 不会默认执行,需要通过
            <Typography.Text type="danger"> run </Typography.Text>来触发执行。
          </Typography.Paragraph>
          <Typography.Text code>
            {`const { loading, run } = useRequest(imitateApi, { manual: true });`}
          </Typography.Text>
        </Typography>
 
        {/* 手动触发 */}
        <Space class="mt-4">
          <Input v-model={[search.value, 'value']} placeholder="Please enter username" />
          <Button type="primary" disabled={loading.value} onClick={() => run(search.value)}>
            {loading.value ? 'Loading' : 'Edit'}
          </Button>
        </Space>
      </Card>
    );
  },
});
 
const Demo3 = defineComponent({
  setup() {
    const search = ref('');
    const setSearch = (value: string) => {
      search.value = value;
    };
 
    const { loading, run } = useRequest(imitateApi, {
      manual: true,
      onBefore: (params) => {
        message.info(`Start Request: ${params[0]}`);
      },
      onSuccess: (result, params) => {
        if (result) {
          setSearch('');
          message.success(`The username was changed to "${params[0]}" !`);
        }
      },
      onError: (error) => {
        message.error(error.message);
      },
      onFinally: () => {
        message.info(`Request finish`);
      },
    });
 
    return () => (
      <Card title="生命周期" class="mt-2">
        <Typography>
          <Typography.Paragraph>
            <Typography.Text type="danger">useRequest </Typography.Text>
            提供了以下几个生命周期配置项,供你在异步函数的不同阶段做一些处理。
          </Typography.Paragraph>
 
          <Typography.Paragraph>
            <Typography.Text code>onBefore</Typography.Text>
            请求之前触发
          </Typography.Paragraph>
 
          <Typography.Paragraph>
            <Typography.Text code>onSuccess</Typography.Text>
            请求成功触发
          </Typography.Paragraph>
 
          <Typography.Paragraph>
            <Typography.Text code>onError</Typography.Text>
            请求失败触发
          </Typography.Paragraph>
 
          <Typography.Paragraph>
            <Typography.Text code>onFinally</Typography.Text>
            请求完成触发
          </Typography.Paragraph>
        </Typography>
 
        {/* 生命周期 */}
        <Space>
          <Input v-model={[search.value, 'value']} placeholder="Please enter username" />
          <Button type="primary" disabled={loading.value} onClick={() => run(search.value, true)}>
            {loading.value ? 'Loading' : 'Edit'}
          </Button>
          <Button danger disabled={loading.value} onClick={() => run(search.value, false)}>
            {loading.value ? 'Loading' : 'Error Edit'}
          </Button>
        </Space>
      </Card>
    );
  },
});
 
const Demo4 = defineComponent({
  setup() {
    const { data, loading, run, refresh } = useRequest(imitateApi, {
      manual: true,
    });
 
    onMounted(() => run('lutz'));
 
    const changeData = () => {
      data.value = `${Date.now()}`;
    };
 
    return () => (
      <Card title="刷新(重复上一次请求)" class="mt-2">
        <Typography>
          <Typography.Paragraph>
            <Typography.Text type="danger">useRequest </Typography.Text>
            提供了
            <Typography.Text type="danger"> refresh </Typography.Text>和
            <Typography.Text type="danger"> refreshAsync </Typography.Text>
            方法,使我们可以使用上一次的参数,重新发起请求。
          </Typography.Paragraph>
        </Typography>
 
        <Spin spinning={loading.value}>
          <Space>
            <div>Username: {data.value}</div>
            <Button type="primary" onClick={changeData}>
              Change data
            </Button>
            <Button onClick={refresh}>Refresh</Button>
          </Space>
        </Spin>
      </Card>
    );
  },
});
 
const Demo5 = defineComponent({
  setup() {
    const search = ref('');
    const setSearch = (value: string) => {
      search.value = value;
    };
 
    const { loading, run, cancel } = useRequest(imitateApi, {
      manual: true,
      onSuccess: (result, params) => {
        if (result) {
          setSearch('');
          message.success(`The username was changed to "${params[0]}" !`);
        }
      },
    });
 
    return () => (
      <Card title="取消响应" class="mt-2">
        <Typography>
          <Typography.Paragraph>
            <Typography.Text type="danger"> useRequest </Typography.Text>提供了
            <Typography.Text type="danger"> cancel </Typography.Text>函数,用于忽略当前 promise
            返回的数据和错误
          </Typography.Paragraph>
        </Typography>
 
        {/* 取消响应 */}
        <Space>
          <Input v-model={[search.value, 'value']} placeholder="Please enter username" />
          <Button type="primary" disabled={loading.value} onClick={() => run(search.value)}>
            Edit
          </Button>
          <Button type="dashed" disabled={!loading.value} onClick={cancel}>
            Cancel
          </Button>
        </Space>
      </Card>
    );
  },
});
 
const Demo6 = defineComponent({
  setup() {
    const search = ref('');
 
    const {
      data: username,
      loading,
      run,
      params,
    } = useRequest(imitateApi, {
      defaultParams: ['lutz'],
    });
 
    const onChange = () => {
      run(search.value);
    };
 
    return () => (
      <Card title="管理参数" class="mt-2">
        <Typography>
          <Typography.Paragraph>
            <Typography.Text type="danger"> useRequest </Typography.Text>返回的
            <Typography.Text type="danger"> params </Typography.Text>会记录当次调用
            <Typography.Text type="danger"> service </Typography.Text>的参数数组。比如你触发了
            <Typography.Text code>run(1, 2, 3)</Typography.Text>,则
            <Typography.Text type="danger"> params </Typography.Text> 等于
            <Typography.Text code> [1, 2, 3] </Typography.Text>
          </Typography.Paragraph>
          <Typography.Paragraph>
            如果我们设置了
            <Typography.Text type="danger"> options.manual = false </Typography.Text>,则首次调用
            <Typography.Text type="danger"> service </Typography.Text>
            的参数可以通过<Typography.Text type="danger"> options.defaultParams </Typography.Text>
            来设置。
          </Typography.Paragraph>
        </Typography>
 
        {/* 管理参数 */}
        <Space>
          <Input v-model={[search.value, 'value']} placeholder="Please enter username" />
          <Button disabled={loading.value} onClick={onChange}>
            {loading.value ? 'Loading' : 'Edit'}
          </Button>
        </Space>
        <div>
          <div>UserId: {unref(params)?.[0]}</div>
          <div>Username: {unref(username)}</div>
        </div>
      </Card>
    );
  },
});
 
export default defineComponent({
  setup() {
    return () => (
      <PageWrapper
        v-slots={{
          headerContent: () => (
            <Typography>
              <Typography.Link
                href="https://ahooks.js.org/zh-CN/hooks/use-request/index"
                target="_blank"
              >
                ahooks{' '}
              </Typography.Link>
              useRequest 的 vue 版本,是一个强大的异步数据管理的 Hooks。
              <Typography.Paragraph>
                <ul>
                  {[
                    '自动请求/手动请求',
                    '轮询',
                    '防抖',
                    '节流',
                    '屏幕聚焦重新请求',
                    '错误重试',
                    'loading delay',
                    'SWR(stale-while-revalidate)',
                    '缓存',
                  ].map((item) => (
                    <li>
                      <Typography.Text>{item}</Typography.Text>
                    </li>
                  ))}
                </ul>
              </Typography.Paragraph>
            </Typography>
          ),
        }}
      >
        <Demo1 />
        <Demo2 />
        <Demo3 />
        <Demo4 />
        <Demo5 />
        <Demo6 />
      </PageWrapper>
    );
  },
});