Skip to content

Commit b668469

Browse files
authored
feat: ✨ use-request support provider option & optimized code
feat: use-request support provider option & optimized code
2 parents 6ac958a + a59288c commit b668469

File tree

24 files changed

+396
-37
lines changed

24 files changed

+396
-37
lines changed

packages/hooks/docs/.vitepress/router.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,9 +151,13 @@ const useRequestRouter = [
151151
link: '/useRequest/scroll/',
152152
},
153153
{
154-
text: '插件',
154+
text: '插件设计',
155155
link: '/useRequest/plugin/',
156156
},
157+
{
158+
text: '全局配置',
159+
link: '/useRequest/global/',
160+
},
157161
],
158162
},
159163
]
@@ -220,9 +224,13 @@ const useRequestRouterEN = [
220224
link: '/en/useRequest/scroll/',
221225
},
222226
{
223-
text: 'Plugins',
227+
text: 'Plugins Design',
224228
link: '/en/useRequest/plugin/',
225229
},
230+
{
231+
text: 'Global Option',
232+
link: '/en/useRequest/global/',
233+
},
226234
],
227235
},
228236
]

packages/hooks/src/index.ts

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
import useRequest, { clearCache } from './useRequest'
1+
import useRequest, {
2+
clearUseRequestCache,
3+
createUseRequest,
4+
useRequestProvider,
5+
} from './useRequest'
26
import useAsyncOrder from './useAsyncOrder'
37
import useBoolean from './useBoolean'
48
import useCookieState from './useCookieState'
@@ -49,7 +53,9 @@ import useWebSocket from './useWebSocket'
4953

5054
export {
5155
useRequest,
52-
clearCache,
56+
clearUseRequestCache,
57+
useRequestProvider,
58+
createUseRequest,
5359
useAsyncOrder,
5460
useBoolean,
5561
useCookieState,
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import type { InjectionKey } from 'vue';
2+
3+
import type { UseRequestOptions } from './types';
4+
5+
const USEREQUEST_GLOBAL_OPTIONS:Record<string,any> = {};
6+
7+
export const USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY: InjectionKey<string> = Symbol(
8+
'USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY',
9+
);
10+
11+
export const setGlobalOptions = (config: UseRequestOptions<unknown,any,[]>) => {
12+
Object.keys(config).forEach(key => {
13+
USEREQUEST_GLOBAL_OPTIONS[key] = config[key as keyof typeof config];
14+
});
15+
};
16+
17+
export const getGlobalOptions = () => {
18+
return USEREQUEST_GLOBAL_OPTIONS;
19+
};
20+
21+
export const clearGlobalOptions = () => {
22+
Object.keys(USEREQUEST_GLOBAL_OPTIONS).forEach(key => {
23+
delete USEREQUEST_GLOBAL_OPTIONS[key];
24+
});
25+
};
26+
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { UseRequestOptions, UseRequestPlugin, UseRequestService } from './types'
2+
import useRequest from './useRequest'
3+
4+
function createUseRequest<
5+
TData,
6+
TParams extends unknown[] = unknown[],
7+
PluginsOptions extends UseRequestPlugin<TData, TParams>[] = UseRequestPlugin<TData, TParams>[]
8+
>(
9+
service: UseRequestService<TData, TParams>,
10+
options?: UseRequestOptions<
11+
TData,
12+
TParams,
13+
PluginsOptions extends (infer P)[]
14+
? P extends UseRequestPlugin<TData, TParams, infer R>
15+
? R
16+
: any
17+
: any
18+
>,
19+
plugins?: PluginsOptions,
20+
) {
21+
return useRequest<TData, TParams, PluginsOptions>(service, options, plugins)
22+
}
23+
24+
export default createUseRequest
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<template>
2+
<demo />
3+
</template>
4+
5+
<script lang="ts" setup>
6+
import { useRequest } from 'vue-hooks-plus'
7+
import { defineComponent, h } from 'vue'
8+
9+
const demo = defineComponent({
10+
setup: () => {
11+
function getUsername(params: { desc: string }): Promise<string> {
12+
return new Promise(resolve => {
13+
setTimeout(() => {
14+
resolve(`vue-hooks-plus ${params.desc}`)
15+
}, 1000)
16+
})
17+
}
18+
const { data, loading } = useRequest(() => getUsername({ desc: 'good' }))
19+
return () => {
20+
return h('div', {}, [
21+
h('div', null, loading.value ? 'loading' : data.value),
22+
h('div', null, data.value),
23+
])
24+
}
25+
},
26+
})
27+
</script>
28+
29+
<style scoped lang="less"></style>
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<template>
2+
<demo1 />
3+
<demo2 />
4+
</template>
5+
6+
<script lang="ts" setup>
7+
import { useRequest, useRequestProvider } from 'vue-hooks-plus'
8+
import { defineComponent, h } from 'vue'
9+
10+
const demo1 = defineComponent({
11+
setup: () => {
12+
function getUsername(params: { desc: string }): Promise<string> {
13+
return new Promise(resolve => {
14+
setTimeout(() => {
15+
resolve(`vue-hooks-plus ${params.desc}`)
16+
}, 1000)
17+
})
18+
}
19+
const { data, loading } = useRequest(() => getUsername({ desc: 'good' }))
20+
return () => {
21+
return h('div', {}, [
22+
h('h3', 'demo1'),
23+
h('div', null, loading.value ? 'loading' : data.value),
24+
])
25+
}
26+
},
27+
})
28+
29+
const DemoGlobal = defineComponent({
30+
setup: () => {
31+
function getUsername(params: { desc: string }): Promise<string> {
32+
return new Promise(resolve => {
33+
setTimeout(() => {
34+
resolve(`vue-hooks-plus ${params.desc}`)
35+
}, 1000)
36+
})
37+
}
38+
const { data, loading } = useRequest(() => getUsername({ desc: 'good' }))
39+
return () => {
40+
return h('div', {}, [
41+
h('h3', 'demo2'),
42+
h('div', null, loading.value ? 'loading' : data.value),
43+
])
44+
}
45+
},
46+
})
47+
48+
const demo2 = defineComponent({
49+
setup: () => {
50+
useRequestProvider({ pollingInterval: 2000 })
51+
return () => {
52+
return h(DemoGlobal)
53+
}
54+
},
55+
})
56+
</script>
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
---
2+
map:
3+
# 映射到docs的路径
4+
path: /useRequest/global/
5+
source:
6+
path: https://github.com/InhiblabCore/vue-hooks-plus/blob/master/packages/hooks/src/useRequest/useRequestProvider.ts
7+
demoPath: https://github.com/InhiblabCore/vue-hooks-plus/blob/master/packages/hooks/src/useRequest/docs/global/demo/demo.vue
8+
---
9+
10+
# Global Option `v1.6.1`
11+
12+
:::tip 🌍 useRequestProvider
13+
14+
Global configuration of `useRequest` based on Provider implementation.
15+
16+
:::
17+
18+
After using `useRequestProvider` to inject configuration, using `useRequest` in its subcomponents will share this configuration.
19+
20+
<demo src="./demo/demo.vue"
21+
language="vue"
22+
title=""
23+
desc="Global configuration, after injecting pollingInterval=2000 in demo2, the request in demo2 will start polling."> </demo>
24+
25+
## API
26+
27+
```typescript
28+
import { useRequestProvider } from 'vue-hooks-plus'
29+
30+
useRequestProvider({ ...options })
31+
```
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
---
2+
map:
3+
# 映射到docs的路径
4+
path: /useRequest/global/
5+
source:
6+
path: https://github.com/InhiblabCore/vue-hooks-plus/blob/master/packages/hooks/src/useRequest/useRequestProvider.ts
7+
demoPath: https://github.com/InhiblabCore/vue-hooks-plus/blob/master/packages/hooks/src/useRequest/docs/global/demo/demo.vue
8+
---
9+
10+
# 全局配置 `v1.6.1`
11+
12+
:::tip 🌍 useRequestProvider
13+
14+
基于 Provider 实现的 `useRequest` 全局配置。
15+
16+
:::
17+
18+
使用了 `useRequestProvider` 注入配置后,其子组件中使用`useRequest` 会共享这份配置。
19+
20+
<demo src="./demo/demo.vue"
21+
language="vue"
22+
title=""
23+
desc="全局配置,demo2 中注入 pollingInterval=2000后,demo2中的请求开始轮询。"> </demo>
24+
25+
## API
26+
27+
```typescript
28+
import { useRequestProvider } from 'vue-hooks-plus'
29+
30+
useRequestProvider({ ...options })
31+
```

packages/hooks/src/useRequest/docs/index.en-US.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ const { data, error, loading } = useRequest(service)
4242

4343
<br />
4444

45-
<demo src="./basic/demo/demo.vue"
45+
<demo src="./basic/demo/Index.vue"
4646
language="vue"
4747
title=""
4848
desc="The fetch request is sent by default"> </demo>

packages/hooks/src/useRequest/docs/index.zh-CN.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ const { data, error, loading } = useRequest(service)
4242

4343
<br />
4444

45-
<demo src="./basic/demo/demo.vue"
45+
<demo src="./basic/demo/Index.vue"
4646
language="vue"
4747
title=""
4848
desc="默认发送获取请求"> </demo>

packages/hooks/src/useRequest/docs/refreshDeps/index.en-US.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ source:
1313

1414
:::tip remark
1515

16-
When the automatic, mode `manual` is not `true` and refreshDeps will take effect.
16+
When the automatic, mode `manual` is not `true` and refreshDeps will take effect.
1717

1818
:::
1919

@@ -26,7 +26,7 @@ When `refreshDeps` passes in an array of responsive objects, when its value chan
2626
title=""
2727
desc="In the example code above, useRequest will execution when it is initialized and Id & store ID changes."> </demo>
2828

29-
## Automatically collect dependencies `>=v1.6.0-alpha.1`
29+
## Automatically collect dependencies `v1.6.0`
3030

3131
When `refreshDeps` is passed in `true`, `useRequest` will automatically collect the response object parameters in the function parameters, as long as the response object in the parameters changes, it will carry the latest value to re-initiate the request.
3232

packages/hooks/src/useRequest/docs/refreshDeps/index.zh-CN.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ source:
2626
title=""
2727
desc="每次参数依赖发生,都会携带参数重新发起请求"> </demo>
2828

29-
## 自动收集依赖 `>=v1.6.0-alpha.1`
29+
## 自动收集依赖 `v1.6.0`
3030

3131
`refreshDeps` 传入的是 `true` 的时候,`useRequest` 会自动收集函数参数中的响应式对象参数,只要参数里面的响应式对象发生变化就会携带最新的值重新发起请求 。
3232

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
import useRequest from "./useRequest";
2-
import { clearCache } from "./utils/cache";
1+
import useRequest from './useRequest'
2+
import useRequestProvider from './useRequestProvider'
3+
import createUseRequest from './createUseRequest'
4+
import { clearCache as clearUseRequestCache } from './utils/cache'
35

4-
export { clearCache };
6+
export { clearUseRequestCache, createUseRequest, useRequestProvider }
57

6-
export default useRequest;
8+
export default useRequest

packages/hooks/src/useRequest/useRequestImplement.ts

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,34 @@
1-
import { ref, reactive, toRefs, onMounted, onUnmounted, unref } from 'vue'
1+
import { ref, reactive, toRefs, onMounted, onUnmounted, unref, inject } from 'vue'
22

33
import Fetch from './Fetch'
4+
import { USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY } from './config'
45
import { UseRequestOptions, UseRequestPlugin, useRequestResult, UseRequestService } from './types'
56

67
function useRequestImplement<TData, TParams extends any[]>(
78
service: UseRequestService<TData, TParams>,
89
options: UseRequestOptions<TData, TParams, any> = {},
910
plugins: UseRequestPlugin<TData, TParams>[] = [],
1011
) {
11-
// 读取配置
12-
const { initialData = undefined, manual = false, ready = true, ...rest } = options
12+
// global option
13+
const USEREQUEST_GLOBAL_OPTIONS = inject<Record<string, any>>(
14+
USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY,
15+
)
16+
// read option
17+
const { initialData = undefined, manual = false, ready = true, ...rest } = {
18+
...(USEREQUEST_GLOBAL_OPTIONS ?? {}),
19+
...(options ?? {}),
20+
} as Record<string, any>
1321

1422
const fetchOptions = {
1523
manual,
1624
ready,
1725
...rest,
1826
}
1927

20-
// 定义一个serviceRef
28+
// serviceRef store service
2129
const serviceRef = ref(service)
2230

23-
// 存储state的响应式对象
31+
// reactive
2432
const state = reactive<{
2533
data?: TData
2634
loading: boolean
@@ -45,7 +53,7 @@ function useRequestImplement<TData, TParams extends any[]>(
4553
}
4654

4755
const initState = plugins.map(p => p?.onInit?.(fetchOptions)).filter(Boolean)
48-
// fetch的实例化
56+
// Fetch Instance
4957
const fetchInstance = new Fetch<TData, TParams>(
5058
serviceRef,
5159
fetchOptions,
@@ -55,20 +63,20 @@ function useRequestImplement<TData, TParams extends any[]>(
5563

5664
fetchInstance.options = fetchOptions
5765

58-
// 运行插件
66+
// run plugins
5967
fetchInstance.pluginImpls = plugins.map(p => {
6068
return p(fetchInstance, fetchOptions)
6169
})
6270

63-
// manual控制是否自动发送请求
71+
// manual
6472
onMounted(() => {
6573
if (!manual) {
6674
const params = fetchInstance.state.params || options.defaultParams || []
6775
if (unref(ready)) fetchInstance.run(...(params as TParams))
6876
}
6977
})
7078

71-
// 组件卸载的时候取消请求
79+
// onUnmounted cancel request
7280
onUnmounted(() => {
7381
fetchInstance.cancel()
7482
})
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { provide } from 'vue';
2+
3+
import { USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY } from './config';
4+
import type { UseRequestOptions } from './types';
5+
6+
export default function useRequestProvider(config: UseRequestOptions<unknown,any,any>){
7+
provide<typeof config>(USEREQUEST_GLOBAL_OPTIONS_PROVIDE_KEY, config);
8+
}

0 commit comments

Comments
 (0)