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:
undefinedThe data returned by request, if formatResult is passed in, the data returned by request will be the formatted
data.
loading
Type:
Ref<boolean>Default:
falseService The execution status of the request
reloading New in 1.2.0
Type:
Ref<boolean>Default:
falseIs 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:
undefinedIf an error is thrown internally, it will be received by
errorand returned.
queries
Type:
Queries<R, P>Default:
ObjectBy default, the newly requested data will overwrite the old requested data. When
queryKey()is enabled,queriescan store the results of multiple requests at the same time, achieving parallel effectsNote
queriesis areactiveopen in new window objectThe types of
Queriesare 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
runmay bePromise<null>
cancel
Type:
() => void- Manually cancel the current request.
- Pause polling.
refresh
reload
Type:
() => voidUsed to clear
queriesdata and all request status (includingdata). Ifmanualisfalse,defaultParamswill 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 aPromisedirectly. You can use third-party request library (such asaxios) to help you generate aPromisefunction 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:
stringDetails:
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:
numberDefault:
0Details:
By setting the delay in milliseconds, you can delay the time loading becomes
true, effectively preventing flicker.See also: Loading Delay
pollingInterval
Type:
numberDefault:
undefinedDetails:
By setting the polling interval's millisecond value, you can enter the polling mode and trigger the request regularly. You can use
run/cancelto enable/stop polling. Whenmanualis set totrue, you need to execute arunbefore starting polling manually.- The interval value must be greater than
0to take effect
- The interval value must be greater than
See also: Polling
pollingWhenHidden
Type:
booleanDefault:
falseDetails:
It takes effect when
pollingIntervalis 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:
booleanDefault:
falseDetails:
It takes effect when
pollingIntervalis 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:
numberDefault:
undefinedDetails:
Enter the debounce mode by setting the number of milliseconds to delay. At this time, if
runis triggered frequently, the request will be made with the debounce strategy.See also: Debounce
debounceOptions New in 1.2.2
- 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:
numberDefault:
undefinedDetails:
Enter the throttling mode by setting the number of milliseconds for throttling. At this time, if
runis triggered frequently, the request will be made with a throttling strategy.See also: Throttle
throttleOptions New in 1.2.2
- 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:
booleanDefault:
falseDetails:
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:
numberDefault:
5000Details:
When refreshOnWindowFocus is set to
true, you can limit the execution interval ofrefreshby setting the interval in milliseconds. The default is 5000ms.See also: RefocusTimespan
cacheKey
Type:
stringDefault:
undefinedDetails:
- We will cache every request
data,error,params,loading - If
cacheKeyis 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:
numberDefault:
600000Details:
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:
numberDefault:
0Details:
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
-1means the cache will never expire.
- The default is
See also: StaleTime
errorRetryCount
Type:
numberDefault:
0Details:
Max error retry count
See also: ErrorRetryCount
errorRetryInterval
Type:
numberDefault:
0Details:
By default, VueRequest uses Binary Exponential Backoff Algorithmopen in new window to help you calculate the appropriate interval time. You can also set
errorRetryIntervalto Override default behavior.See also: ErrorRetryInterval
manual
Type:
booleanDefault:
falseDetails:
When
manualis set totrue, you need to manually triggerrunto initiate the request.See also: Manually Trigger
defaultParams
Type:
P[]Default:
[]Details:
If
manualis set tofalse, when the run is automatically executed,defaultParamswill be used as the request parameter.
ready
Type:
Ref<boolean>Default:
trueDetails:
Only when
readyistruewill the request be initiated.- This behavior is only triggered once. If you want to trigger multiple times, it is recommended to use
refreshDepsor 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:
RDefault:
undefinedDetails:
Initialized
data.
refreshDeps
Type:
WatchSource<any>[]Default:
[]Details:
The change of
refreshDepswill trigger the re-execution ofrefresh. Its essence is just an encapsulation ofwatchopen in new windowwatch(refreshDeps, refresh);See also: Dependency Refresh
queryKey
Type:
(...params: P[]) => stringDetails:
According to params, get the key of the current request. After setting, we will maintain the request status with different key values in
queriesat the same time.See also: Concurrent Request
formatResult
Type:
(data: R) => FRDetails:
Format the request result, the input parameter is the
datareturned 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[]) => voidDetails:
Triggered when Service
resolve, the parameters aredataandparams.- If there is
formatResult, thendatais the formatted data.
- If there is
onError
Type:
(error: Error, params: P[]) => voidDetails:
Triggered when Service
reject, the parameters areerrorandparams.
