Public API
VueRequest usually consists of three parts: Return Values, Service, and Options
const { ...ReturnValues } = useRequest<R, P, FR>(Service, Options);
TS Generic description
R
is a generic type of data
.
P
is a generic of params
. (Note: This generic is subject to unknown[]
constraints)
FR
is the type of data
returned by formatResult
. (Note: The R
generics mentioned in the following documents, after using formatResult
, use FR
instead)
Return Values
data
Type:
Ref<R | undefined>
Default:
undefined
The data returned by request, if formatResult is passed in, the data returned by request will be the formatted
data
.
loading
Type:
Ref<boolean>
Default:
false
Service The execution status of the request
New in 1.2.0
reloadingType:
Ref<boolean>
Default:
false
Is reloading, used to record whether
reload()
is triggering.
params
Type:
Ref<P[]>
Default:
[]
Service request parameters
Usage:
function getUser(name) {
return fetch('api/user?' + new URLSearchParams({ name })).then(res => res.json());
}
const { params, run } = useRequest(getUser, {
defaultParams: ['John'],
});
// In the default request, if defaultParams exists, params. the value will be equal to defaultParams. Otherwise, it will be an empty array.
// When run passes in parameters, the parameters at this time will be synchronized to params
run('Benny'); // params.value is ['Benny']
error
Type:
Ref<Error | undefined>
Default:
undefined
If an error is thrown internally, it will be received by
error
and returned.
queries
Type:
Queries<R, P>
Default:
Object
By default, the newly requested data will overwrite the old requested data. When
queryKey()
is enabled,queries
can store the results of multiple requests at the same time, achieving parallel effectsNote
queries
is areactive
open in new window objectThe types of
Queries
are as follows.type Queries<R, P> = { loading: boolean; data: R | undefined; error: Error | undefined; params: P[]; run: (...params: P[]) => Promise<R>; cancel: () => void; refresh: () => Promise<R>; mutate: (arg: (oldData: R) => R) => void | (newData: R) => void; }
See also: Concurrent Request
run
Type:
(...params: P[]) => Promise<R>
Manually trigger the request of Service
Note
When debounceInterval or throttleInterval mode is enabled. The return result of
run
may bePromise<null>
cancel
Type:
() => void
- Manually cancel the current request.
- Pause polling.
refresh
reload
Type:
() => void
Used to clear
queries
data and all request status (includingdata
). Ifmanual
isfalse
,defaultParams
will be used to trigger againrun()
.
mutate
Service
For the request. See also Data Fetching
Request Method
Type:
(...params: P[]) => Promise<R>
| (...params: P[]) => string
| (...params: P[]) => ({ url: string; [key: string]: any; })
Details:
You can pass in a function whose return value is
Promise
, String or Object. We recommend returning aPromise
directly. You can use third-party request library (such asaxios
) to help you generate aPromise
function for initiating a request to obtain resources.import { useRequest } from 'vue-request'; import axios from 'axios'; const getUser = () => { return axios.get('api/user'); }; const { data } = useRequest(getUser);
String
Type:
string
Details:
If you pass in a string or call it by returning a string from Request Method, then we will use the global
fetch()
open in new window method to initiate a request to obtain resources, this string will be used as the URL for obtaining resources
Object
Type:
{ url: string; [key: string]: any; }
Details:
If you pass in an object or call it by returning an object via Request Method, then we will use the global
fetch()
open in new window method to initiate a request for resources. The object must contain a key-value pair named URL, which will be used as the URL for obtaining resources.
Options
loadingDelay
Type:
number
Default:
0
Details:
By setting the delay in milliseconds, you can delay the time loading becomes
true
, effectively preventing flicker.See also: Loading Delay
pollingInterval
Type:
number
Default:
undefined
Details:
By setting the polling interval's millisecond value, you can enter the polling mode and trigger the request regularly. You can use
run
/cancel
to enable/stop polling. Whenmanual
is set totrue
, you need to execute arun
before starting polling manually.- 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:
It takes effect when
pollingInterval
is greater than0
. By default, polling will be suspended when the screen is not visible. When set totrue
, polling tasks will still be executed regularly when the screen is not visible.See also: PollingWhenHidden
pollingWhenOffline
Type:
boolean
Default:
false
Details:
It takes effect when
pollingInterval
is greater than0
. By default, polling will be suspended when the network is unavailable. When set totrue
, the polling task will still be executed regularly when the network is not available.See also: PollingWhenOffline
debounceInterval
Type:
number
Default:
undefined
Details:
Enter the debounce mode by setting the number of milliseconds to delay. At this time, if
run
is triggered frequently, the request will be made with the debounce strategy.See also: Debounce
New in 1.2.2
debounceOptions- Type:
Object
- Default:
{
leading: false,
maxWait: undefined,
trailing: true
}
Details:
leading
(boolean): Specify invoking on the leading edge of the timeout.maxWait
(number): The maximum time request function is allowed to be delayed before it's invoked.trailing
(boolean): Specify invoking on the trailing edge of the timeout.
throttleInterval
Type:
number
Default:
undefined
Details:
Enter the throttling mode by setting the number of milliseconds for throttling. At this time, if
run
is triggered frequently, the request will be made with a throttling strategy.See also: Throttle
New in 1.2.2
throttleOptions- Type:
Object
- Default:
{
leading: true,
trailing: true,
}
Details:
leading
(boolean): Specify invoking on the leading edge of the timeout.trailing
(boolean): Specify invoking on the trailing edge of the timeout.
refreshOnWindowFocus
Type:
boolean
Default:
false
Details:
When set to
true
, focusopen in new window and visibilitychangeopen in new window, the request will be re-initiated.See also: Refresh On Focus
refocusTimespan
Type:
number
Default:
5000
Details:
When refreshOnWindowFocus is set to
true
, you can limit the execution interval ofrefresh
by setting the interval in milliseconds. The default is 5000ms.See also: RefocusTimespan
cacheKey
Type:
string
Default:
undefined
Details:
- We will cache every request
data
,error
,params
,loading
- If
cacheKey
is set, VueRequest will cache the current request data. When the next component is initialized, if there is cached data, we will return the cached data first and then send a new request behind the scenes. After the new data is returned, we will trigger the data update and update the cached data again, which is the ability of SWR. - The request for the same cacheKey is shared globally. i.e., you can load data in advance. With this feature, preloading can be easily achieved.
- We will cache every request
See also: Cache / Preload
cacheTime
Type:
number
Default:
600000
Details:
When the cache is turned on, you can tell us the cache's expiration time by setting
cacheTime
. When the cache expires, we will delete it. The default 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 in a certain period of time, we recommend that you set a reasonable number of milliseconds.
- The default is
0
, which means no preservation, and the request will be reissued every time. - Set to
-1
means the cache will never expire.
- The default is
See also: StaleTime
errorRetryCount
Type:
number
Default:
0
Details:
Max error retry count
See also: ErrorRetryCount
errorRetryInterval
Type:
number
Default:
0
Details:
By default, VueRequest uses Binary Exponential Backoff Algorithmopen in new window to help you calculate the appropriate interval time. You can also set
errorRetryInterval
to Override default behavior.See also: ErrorRetryInterval
manual
Type:
boolean
Default:
false
Details:
When
manual
is set totrue
, you need to manually triggerrun
to initiate the request.See also: Manually Trigger
defaultParams
Type:
P[]
Default:
[]
Details:
If
manual
is set tofalse
, when the run is automatically executed,defaultParams
will be used as the request parameter.
ready
Type:
Ref<boolean>
Default:
true
Details:
Only when
ready
istrue
will the request be initiated.- This behavior is only triggered once. If you want to trigger multiple times, it is recommended to use
refreshDeps
or implement the relevant logic yourself.
- This behavior is only triggered once. If you want to trigger multiple times, it is recommended to use
See also: Dependent Request
initialData
Type:
R
Default:
undefined
Details:
Initialized
data
.
refreshDeps
Type:
WatchSource<any>[]
Default:
[]
Details:
The change of
refreshDeps
will trigger the re-execution ofrefresh
. Its essence is just an encapsulation ofwatch
open in new windowwatch(refreshDeps, refresh);
See also: Dependency Refresh
queryKey
Type:
(...params: P[]) => string
Details:
According to params, get the key of the current request. After setting, we will maintain the request status with different key values in
queries
at the same time.See also: Concurrent Request
formatResult
Type:
(data: R) => FR
Details:
Format the request result, the input parameter is the
data
returned by the original interface, and the output parameter is the processeddata
.import { defineComponent } from 'vue'; import { useRequest } from 'vue-request'; export default defineComponent({ name: 'App', setup() { const { data } = useRequest<number, any, string>('api/timestramp', { formatResult: data => { return new Date(data); }, }); return () => <div>{data.value}</div>; }, });
onSuccess
Type:
(data: R, params: P[]) => void
Details:
Triggered when Service
resolve
, the parameters aredata
andparams
.- If there is
formatResult
, thendata
is the formatted data.
- If there is
onError
Type:
(error: Error, params: P[]) => void
Details:
Triggered when Service
reject
, the parameters areerror
andparams
.