Public API
VueRequest usually consists of three parts: Return Values, Service, and Options.
const { ...ReturnValues } = useRequest<R, P>(Service, Options);
TypeScript Generics Explanation
R is the generic type for the returned data.
P is the generic type for params, which is constrained by unknown[].
Return Values
data
Type:
shallowRef<R | undefined>Default:
undefinedThe data returned from the API.
loading
Type:
Ref<boolean>Default:
falseThe execution status of a request for the Service.
params
Type:
Ref<P[]>Default:
[]The request parameters for the Service request.
Usage:
function getUser(name, age) { return axios.get('api/user', { params: { name: name, age: age, }, }); } const { params, run } = useRequest(getUser, { defaultParams: ['John', 18], }); // When making a default request, if defaultParams exist, params.value will be equal to defaultParams, otherwise it will be an empty array. // When run is called with arguments, the arguments will be synchronized to the params array. run('Benny', 18); // params.value will be equal to ['Benny', 18]
error
Type:
shallowRef<Error | undefined>Default:
undefinedIf an error is thrown internally, it will be caught and returned by
error.
run
Type: ``(...params: P[]) => void`
To manually trigger a request for the Service. It will automatically catch exceptions and handle them through
options.onError.
runAsync
Type:
(...params: P[]) => Promise<R>It is used in the same way as
run, but it returns aPromiseand you need to handle exceptions yourself.
cancel
Type:
() => void- Manually cancel the current request.
- Stop the polling function.
refresh
Type:
() => voidRe-call
runwith the last params used.
refreshAsync
Type:
() => Promise<R>Re-call
runAsyncwith the last params used.
mutate
Type:
(arg: (oldData: R) => R) => void | (newData: R) => voidDirectly modify the result of data.
See also: Mutation
Service
Request Method
Type:
(...params: P[]) => Promise<R>Details:
This is used to initiate a request for resources, and you can refer to Data Fetching.
A
Servicemust be a function that returns aPromise. You can use third-party request libraries (such asaxios) to generate aPromisefunction that is used to initiate a request for resources.import { useRequest } from 'vue-request'; import axios from 'axios'; const getUser = () => { return axios.get('api/user'); }; const { data } = useRequest(getUser);
Options
loadingDelay reactivity
Type:
number | Ref<number>Default:
0Details:
By setting the delay in milliseconds, you can delay the transition of loading to
true, which effectively prevents flickering.See also: Loading State
loadingKeep reactivity
Type:
number | Ref<number>Default:
0Details:
You can keep the loading animation for a certain amount of time.
See also: Loading State
pollingInterval reactivity
Type:
number | Ref<number>Default:
undefinedDetails:
By setting the polling interval in milliseconds, you can enter polling mode and trigger requests at regular intervals. You can use
run/cancelto start/stop polling. Whenmanualis set totrue, you need to manually executerunonce before polling starts.- The interval value must be greater than
0to take effect.
- The interval value must be greater than
See also: Polling
pollingWhenHidden
Type:
booleanDefault:
falseDetails:
This only takes effect when
pollingIntervalis greater than0. By default, polling is paused when the screen is not visible. When set totrue, polling tasks will continue to be executed at regular intervals even when the screen is not visible.See also: PollingWhenHidden
pollingWhenOffline
Type:
booleanDefault:
falseDetails:
This only takes effect when
pollingIntervalis greater than0. By default, polling is paused when the network is not available. When set totrue, polling tasks will continue to be executed at regular intervals even when the network is not available.See also: PollingWhenOffline
debounceInterval reactivity
Type:
number | Ref<number>Default:
undefinedDetails:
By setting the number of milliseconds to delay, you can enter debounce mode. In this mode, if requests are triggered frequently, they will be sent according to a debounce strategy.
See also: Debounce
debounceOptions reactivity
Type:
DebounceOptions | Reactive<DebounceOptions>type DebounceOptions = { leading: boolean; maxWait: number; trailing: boolean; };Default:
{ leading: false, maxWait: undefined, trailing: true }Details:
leading(boolean): Specifies whether the request method should be called before the delay.maxWait(number): Sets the maximum delay allowed for the request method.trailing(boolean): Specifies whether the request method should be called after the delay has ended.
throttleInterval reactivity
Type:
number | Ref<number>Default:
undefinedDetails:
By setting the number of milliseconds to throttle, you can enter throttle mode. In this mode, if requests are triggered frequently, they will be sent according to a throttle strategy.
See also: Throttle
throttleOptions reactivity
Type:
ThrottleOptions | Reactive<ThrottleOptions>type ThrottleOptions = { leading: boolean; trailing: boolean; };Default:
{ leading: true, trailing: true, }Details:
leading(boolean): Specifies whether the call should be made before the throttle starts.trailing(boolean): Specifies whether the call should be made after the throttle ends.
refreshOnWindowFocus reactivity
Type:
boolean | Ref<boolean>Default:
falseDetails:
When set to
true, requests will be resent when the browser window triggers focusopen in new window and visibilitychangeopen in new window events.See also: Refresh On Focus
refocusTimespan reactivity
Type:
number | Ref<number>Default:
5 * 1000Details:
When refreshOnWindowFocus is set to
true, you can limit the interval betweenrefreshexecutions by setting the interval in milliseconds. The default interval is 5000ms.See also: RefocusTimespan
cacheKey
Type:
string | (params?: P) => stringDefault:
undefinedDetails:
- We cache
data,error,params, andloadingfor each request. - If
cacheKeyis set, VueRequest will cache the current request data. When the component is initialized next time, if there is cached data, we will return the cached data first, and then send a new request in the background. After the new data is returned, we will trigger a data update and update the cached data, which is the ability of SWR. - Data synchronization: whenever we change the content of a
cacheKey, other data with the samecacheKeywill also be synchronized. - Request
Promisesharing: Only one requestPromisewill be initiated at the same time for the samecacheKey, and the later request will share the same requestPromise.
- We cache
See also: Cache / Preload
cacheTime
Type:
numberDefault:
10* 60 * 1000Details:
When caching is enabled, you can set
cacheTimeto tell us the expiration time of the cache. When the cache expires, we will delete it. The default value is 600000 milliseconds, which is 10 minutes.See also: CacheTime
staleTime
Type:
numberDefault:
0Details:
If you can ensure that the cached data will not be updated for a certain period of time, we recommend that you set a reasonable number of milliseconds.
- The default value is
0, which means that the data is not fresh and a new request will be sent every time. - Setting it to
-1means that the cache will never expire.
- The default value is
See also: StaleTime
setCache
Type:
(cacheKey: string, cacheData: CacheData) => voidtype CacheData = { data: R; params: P; time: number; };Details:
You can customize cache settings.
参考: Custom cache
getCache
Type:
(cacheKey: string) => CacheDatatype CacheData = { data: R; params: P; time: number; };Details:
You can customize how to read cache.
参考: Custom cache
errorRetryCount reactivity
Type:
number | Ref<number>Default:
0Details:
Maximum number of error retries.
See also: ErrorRetryCount
errorRetryInterval reactivity
Type:
number | Ref<number>Default:
0Details:
By default, VueRequest uses the Exponential Backoff Algorithmopen in new window to calculate the appropriate interval for you. You can also override the default behavior by setting
errorRetryInterval.See also: ErrorRetryInterval
manual
Type:
booleanDefault:
falseDetails:
When
manualis set totrue, you need to manually triggerrunorrunAsyncto initiate the request.See also: Manually Trigger
defaultParams
Type:
P[]Default:
[]Details:
If
manualis set tofalse,defaultParamswill be used as the request parameters when the request is automatically executed.
ready reactivity
Type:
Ref<boolean> | () => booleanDefault:
trueDetails:
The request will only be sent when
readyistrue.- Automatic mode: When
manualis set tofalse, a request will be automatically sent every timereadychanges fromfalsetotrue, and the request will include theoptions.defaultParamsparameters. - Manual mode: When
manualis set totrue, no request can be sent as long asreadyisfalse.
- Automatic mode: When
See also: Dependent Request
initialData
Type:
RDefault:
undefinedDetails:
Default value for
data.
refreshDeps
Type:
WatchSource<any> | WatchSource<any>[]Default:
[]Details:
When the contents of
refreshDepschange andrefreshDepsActionis not set, therefreshwill be triggered to execute again. Essentially, this is just a wrapper forwatchopen in new window.watch(refreshDeps, refresh);See also: Dependency Refresh
refreshDepsAction
Type:
() => voidDetails:
It will be called when the contents of
refreshDepschange. It will also be triggered whenmanualis set totrue.See also: refreshDepsAction
onSuccess
Type:
(data: R, params: P[]) => voidDetails:
It is triggered when Service
resolveis called withdataandparamsas parameters.
onError
Type:
(error: Error, params: P[]) => voidDetails:
It is triggered when Service
rejectis called witherrorandparamsas parameters.
onBefore
Type:
(params: P[]) => voidDetails:
It is triggered before the Service request with
paramsas a parameter.
