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:
undefined
The data returned from the API.
loading
Type:
Ref<boolean>
Default:
false
The 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:
undefined
If 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 aPromise
and you need to handle exceptions yourself.
cancel
Type:
() => void
- Manually cancel the current request.
- Stop the polling function.
refresh
Type:
() => void
Re-call
run
with the last params used.
refreshAsync
Type:
() => Promise<R>
Re-call
runAsync
with the last params used.
mutate
Type:
(arg: (oldData: R) => R) => void | (newData: R) => void
Directly 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
Service
must be a function that returns aPromise
. You can use third-party request libraries (such asaxios
) to generate aPromise
function 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
reactivity
loadingDelayType:
number | Ref<number>
Default:
0
Details:
By setting the delay in milliseconds, you can delay the transition of loading to
true
, which effectively prevents flickering.See also: Loading State
reactivity
loadingKeepType:
number | Ref<number>
Default:
0
Details:
You can keep the loading animation for a certain amount of time.
See also: Loading State
reactivity
pollingIntervalType:
number | Ref<number>
Default:
undefined
Details:
By setting the polling interval in milliseconds, you can enter polling mode and trigger requests at regular intervals. You can use
run
/cancel
to start/stop polling. Whenmanual
is set totrue
, you need to manually executerun
once before polling starts.- The interval value must be greater than
0
to take effect.
- The interval value must be greater than
See also: Polling
pollingWhenHidden
Type:
boolean
Default:
false
Details:
This only takes effect when
pollingInterval
is 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:
boolean
Default:
false
Details:
This only takes effect when
pollingInterval
is 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
reactivity
debounceIntervalType:
number | Ref<number>
Default:
undefined
Details:
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
reactivity
debounceOptionsType:
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.
reactivity
throttleIntervalType:
number | Ref<number>
Default:
undefined
Details:
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
reactivity
throttleOptionsType:
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.
reactivity
refreshOnWindowFocusType:
boolean | Ref<boolean>
Default:
false
Details:
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
reactivity
refocusTimespanType:
number | Ref<number>
Default:
5 * 1000
Details:
When refreshOnWindowFocus is set to
true
, you can limit the interval betweenrefresh
executions by setting the interval in milliseconds. The default interval is 5000ms.See also: RefocusTimespan
cacheKey
Type:
string | (params?: P) => string
Default:
undefined
Details:
- We cache
data
,error
,params
, andloading
for each request. - If
cacheKey
is 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 samecacheKey
will also be synchronized. - Request
Promise
sharing: Only one requestPromise
will 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:
number
Default:
10* 60 * 1000
Details:
When caching is enabled, you can set
cacheTime
to 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:
number
Default:
0
Details:
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
-1
means that the cache will never expire.
- The default value is
See also: StaleTime
setCache
Type:
(cacheKey: string, cacheData: CacheData) => void
type CacheData = { data: R; params: P; time: number; };
Details:
You can customize cache settings.
参考: Custom cache
getCache
Type:
(cacheKey: string) => CacheData
type CacheData = { data: R; params: P; time: number; };
Details:
You can customize how to read cache.
参考: Custom cache
reactivity
errorRetryCountType:
number | Ref<number>
Default:
0
Details:
Maximum number of error retries.
See also: ErrorRetryCount
reactivity
errorRetryIntervalType:
number | Ref<number>
Default:
0
Details:
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:
boolean
Default:
false
Details:
When
manual
is set totrue
, you need to manually triggerrun
orrunAsync
to initiate the request.See also: Manually Trigger
defaultParams
Type:
P[]
Default:
[]
Details:
If
manual
is set tofalse
,defaultParams
will be used as the request parameters when the request is automatically executed.
reactivity
readyType:
Ref<boolean> | () => boolean
Default:
true
Details:
The request will only be sent when
ready
istrue
.- Automatic mode: When
manual
is set tofalse
, a request will be automatically sent every timeready
changes fromfalse
totrue
, and the request will include theoptions.defaultParams
parameters. - Manual mode: When
manual
is set totrue
, no request can be sent as long asready
isfalse
.
- Automatic mode: When
See also: Dependent Request
initialData
Type:
R
Default:
undefined
Details:
Default value for
data
.
refreshDeps
Type:
WatchSource<any> | WatchSource<any>[]
Default:
[]
Details:
When the contents of
refreshDeps
change andrefreshDepsAction
is not set, therefresh
will be triggered to execute again. Essentially, this is just a wrapper forwatch
open in new window.watch(refreshDeps, refresh);
See also: Dependency Refresh
refreshDepsAction
Type:
() => void
Details:
It will be called when the contents of
refreshDeps
change. It will also be triggered whenmanual
is set totrue
.See also: refreshDepsAction
onSuccess
Type:
(data: R, params: P[]) => void
Details:
It is triggered when Service
resolve
is called withdata
andparams
as parameters.
onError
Type:
(error: Error, params: P[]) => void
Details:
It is triggered when Service
reject
is called witherror
andparams
as parameters.
onBefore
Type:
(params: P[]) => void
Details:
It is triggered before the Service request with
params
as a parameter.