Ben Lin
2025-03-08 72675157c774fc4c6490bd1e49ca3c4aa25581f0
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
import { defineComponent, ref, unref } from 'vue';
import { Card, Typography, Button, Input, Space, message } from 'ant-design-vue';
import { getArticle } from './mock-api';
import { useRequest, clearCache } from '@vben/hooks';
import { PageWrapper } from '@/components/Page';
 
const Article1 = defineComponent({
  props: {
    cacheKey: {
      type: String,
      default: 'cacheKey-demo',
    },
  },
  setup(props) {
    const { loading, data } = useRequest(getArticle, {
      cacheKey: props.cacheKey,
    });
 
    return () => (
      <>
        <p>Background loading: {loading.value ? 'true' : 'false'}</p>
        <p>Latest request time: {unref(data)?.time}</p>
        <p>{unref(data)?.data}</p>
      </>
    );
  },
});
 
const Demo1 = defineComponent({
  setup() {
    const state = ref(false);
    const toggle = (bool?: boolean) => {
      state.value = bool ?? !state.value;
    };
 
    return () => (
      <Card title="SWR">
        <Typography>
          <Typography.Paragraph>
            下面的示例,我们设置了
            <Typography.Text type="danger"> cacheKey </Typography.Text>
            ,在组件第二次加载时,会优先返回缓存的内容,然后在背后重新发起请求。你可以通过点击按钮来体验效果。
          </Typography.Paragraph>
        </Typography>
 
        {/* SWR */}
        <div class="mt-4">
          <Button type="primary" onClick={() => toggle()}>
            {state.value ? 'hidden' : 'show'}
          </Button>
          {state.value && <Article1 />}
        </div>
      </Card>
    );
  },
});
 
const Article2 = defineComponent({
  setup() {
    const { loading, data } = useRequest(getArticle, {
      cacheKey: 'staleTime-demo',
      staleTime: 5000,
    });
 
    return () => (
      <>
        <p>Background loading: {loading.value ? 'true' : 'false'}</p>
        <p>Latest request time: {unref(data)?.time}</p>
        <p>{unref(data)?.data}</p>
      </>
    );
  },
});
 
const Demo2 = defineComponent({
  setup() {
    const state = ref(false);
    const toggle = (bool?: boolean) => {
      state.value = bool ?? !state.value;
    };
 
    return () => (
      <Card title="数据保持新鲜" class="mt-2">
        <Typography>
          <Typography.Paragraph>
            通过设置
            <Typography.Text type="danger"> staleTime </Typography.Text>
            ,我们可以指定数据新鲜时间,在这个时间内,不会重新发起请求。下面的示例设置了 5s
            的新鲜时间,你可以通过点击按钮来体验效果
          </Typography.Paragraph>
        </Typography>
 
        {/* 数据保持新鲜 */}
        <div class="mt-4">
          <Button type="primary" onClick={() => toggle()}>
            {state.value ? 'hidden' : 'show'}
          </Button>
          {state.value && <Article2 />}
        </div>
      </Card>
    );
  },
});
 
const Article3 = defineComponent({
  setup() {
    const { loading, data, refresh } = useRequest(getArticle, {
      cacheKey: 'cacheKey-share',
    });
 
    return () => (
      <>
        <p>Background loading: {loading.value ? 'true' : 'false'}</p>
        <Button type="primary" onClick={refresh}>
          更新
        </Button>
        <p>Latest request time: {unref(data)?.time}</p>
        <p>{unref(data)?.data}</p>
      </>
    );
  },
});
 
const Demo3 = defineComponent({
  setup() {
    return () => (
      <Card title="数据共享" class="mt-2">
        <Typography>
          <Typography.Paragraph>
            同一个<Typography.Text type="danger"> cacheKey </Typography.Text>
            的内容,在全局是共享的,这会带来以下几个特性
          </Typography.Paragraph>
 
          <Typography.Paragraph>
            <ul>
              <li>
                请求 Promise 共享,相同的<Typography.Text type="danger"> cacheKey </Typography.Text>
                同时只会有一个在发起请求,后发起的会共用同一个请求 Promise
              </li>
              <li>
                数据同步,任何时候,当我们改变其中某个 cacheKey 的内容时,其它相同
                <Typography.Text type="danger"> cacheKey </Typography.Text>
                的内容均会同步
              </li>
            </ul>
          </Typography.Paragraph>
        </Typography>
 
        {/* 数据共享 */}
        <div class="mt-4">
          <h2>Article 1</h2>
          <Article3 />
          <h2>Article 2</h2>
          <Article3 />
        </div>
      </Card>
    );
  },
});
 
const Article4 = defineComponent({
  setup() {
    const { loading, data, params, run } = useRequest(getArticle, {
      cacheKey: 'cacheKey-share4',
    });
 
    const keyword = ref(params.value?.[0] || '');
 
    return () => (
      <>
        <Space>
          <Input v-model={[keyword.value, 'value']} />
          <Button onClick={() => run(keyword.value)}>Get</Button>
        </Space>
        <p>Background loading: {loading.value ? 'true' : 'false'}</p>
        <p>Latest request time: {unref(data)?.time}</p>
        <p>Latest request data: {unref(data)?.data}</p>
        <p>keyword: {keyword.value}</p>
      </>
    );
  },
});
 
const Demo4 = defineComponent({
  setup() {
    const state = ref(false);
    const toggle = (bool?: boolean) => {
      state.value = bool ?? !state.value;
    };
 
    return () => (
      <Card title="参数缓存" class="mt-2">
        <Typography>
          <Typography.Paragraph>
            缓存的数据包括 data 和 params,通过 params
            缓存机制,我们可以记忆上一次请求的条件,并在下次初始化
          </Typography.Paragraph>
        </Typography>
 
        {/* 参数缓存 */}
        <div class="mt-4">
          <Button type="primary" onClick={() => toggle()}>
            {state.value ? 'hidden' : 'show'}
          </Button>
          <div class="mt-2">{state.value && <Article4 />}</div>
        </div>
      </Card>
    );
  },
});
 
const Demo5 = defineComponent({
  setup() {
    const state = ref(false);
    const toggle = (bool?: boolean) => {
      state.value = bool ?? !state.value;
    };
 
    const clear = (cacheKey?: string | string[]) => {
      clearCache(cacheKey);
      const tips = Array.isArray(cacheKey) ? cacheKey.join('、') : cacheKey;
      message.success(`Clear ${tips ?? 'All'} finished`);
    };
 
    return () => (
      <Card title="删除缓存" class="mt-2">
        <Typography>
          <Typography.Paragraph>
            useRequest 提供了一个 clearCache 方法,可以清除指定 cacheKey 的缓存数据。
          </Typography.Paragraph>
        </Typography>
 
        {/* 删除缓存 */}
        <div class="mt-4">
          <Space>
            <Button type="primary" onClick={() => toggle()}>
              {state.value ? 'hidden' : 'show'}
            </Button>
            <Button onClick={() => clear('Article1')}>Clear Article1</Button>
            <Button onClick={() => clear('Article2')}>Clear Article2</Button>
            <Button onClick={() => clear(['Article2', 'Article3'])}>
              Clear Article2 and Article3
            </Button>
            <Button onClick={() => clear()}>Clear All</Button>
          </Space>
          <h2>Article 1</h2>
          {state.value && <Article1 cacheKey="Article1" />}
          <h2>Article 2</h2>
          {state.value && <Article1 cacheKey="Article2" />}
          <h2>Article 3</h2>
          {state.value && <Article1 cacheKey="Article3" />}
        </div>
      </Card>
    );
  },
});
 
const Article6 = defineComponent({
  setup() {
    const cacheKey = 'setCache-demo6';
    const { loading, data } = useRequest(getArticle, {
      cacheKey,
      setCache: (data) => localStorage.setItem(cacheKey, JSON.stringify(data)),
      getCache: () => JSON.parse(localStorage.getItem(cacheKey) || '{}'),
    });
 
    return () => (
      <>
        <p>Background loading: {loading.value ? 'true' : 'false'}</p>
        <p>Latest request time: {unref(data)?.time}</p>
        <p>{unref(data)?.data}</p>
      </>
    );
  },
});
 
const Demo6 = defineComponent({
  setup() {
    const state = ref(false);
    const toggle = (bool?: boolean) => {
      state.value = bool ?? !state.value;
    };
 
    return () => (
      <Card title="自定义缓存" class="mt-2">
        <Typography>
          <Typography.Paragraph>
            通过配置 setCache 和 getCache,可以自定义数据缓存,比如可以将数据存储到
            localStorage、IndexDB 等。
          </Typography.Paragraph>
        </Typography>
 
        {/* 自定义缓存 */}
        <div class="mt-4">
          <Button type="primary" onClick={() => toggle()}>
            {state.value ? 'hidden' : 'show'}
          </Button>
          <div class="mt-2">{state.value && <Article6 />}</div>
        </div>
      </Card>
    );
  },
});
 
export default defineComponent({
  setup() {
    return () => (
      <PageWrapper>
        <Demo1 />
        <Demo2 />
        <Demo3 />
        <Demo4 />
        <Demo5 />
        <Demo6 />
      </PageWrapper>
    );
  },
});