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 a Promise and you need to handle exceptions yourself.

cancel

  • Type: () => void

    • Manually cancel the current request.
    • Stop the polling function.

    Note

    Here the term "cancel" does not actually stop the request. It only cancels the assignment of data and resets loading to false. The current outgoing API request will continue to be processed.

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 a Promise. You can use third-party request libraries (such as axios) to generate a Promise 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

loadingDelay reactivity

  • Type: 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

loadingKeep reactivity

  • Type: number | Ref<number>

  • Default: 0

  • Details:

    You can keep the loading animation for a certain amount of time.

  • See also: Loading State

pollingInterval reactivity

  • Type: 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. When manual is set to true, you need to manually execute run once before polling starts.

    • The interval value must be greater than 0 to take effect.
  • See also: Polling

pollingWhenHidden

  • Type: boolean

  • Default: false

  • Details:

    This only takes effect when pollingInterval is greater than 0. By default, polling is paused when the screen is not visible. When set to true, 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 than 0. By default, polling is paused when the network is not available. When set to true, 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: 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

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: 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

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

refocusTimespan reactivity

  • Type: number | Ref<number>

  • Default: 5 * 1000

  • Details:

    When refreshOnWindowFocus is set to true, you can limit the interval between refresh 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, and loading 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 same cacheKey will also be synchronized.
    • Request Promise sharing: Only one request Promise will be initiated at the same time for the same cacheKey, and the later request will share the same request Promise.
  • 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.
  • 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

errorRetryCount reactivity

  • Type: number | Ref<number>

  • Default: 0

  • Details:

    Maximum number of error retries.

  • See also: ErrorRetryCount

errorRetryInterval reactivity

manual

  • Type: boolean

  • Default: false

  • Details:

    When manual is set to true, you need to manually trigger run or runAsync to initiate the request.

  • See also: Manually Trigger

defaultParams

  • Type: P[]

  • Default: []

  • Details:

    If manual is set to false, defaultParams will be used as the request parameters when the request is automatically executed.

ready reactivity

  • Type: Ref<boolean> | () => boolean

  • Default: true

  • Details:

    The request will only be sent when ready is true.

    • Automatic mode: When manual is set to false, a request will be automatically sent every time ready changes from false to true, and the request will include the options.defaultParams parameters.
    • Manual mode: When manual is set to true, no request can be sent as long as ready is false.
  • 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 and refreshDepsAction is not set, the refresh will be triggered to execute again. Essentially, this is just a wrapper for watchopen 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 when manual is set to true.

  • See also: refreshDepsAction

onSuccess

  • Type: (data: R, params: P[]) => void

  • Details:

    It is triggered when Service resolve is called with data and params as parameters.

onError

  • Type: (error: Error, params: P[]) => void

  • Details:

    It is triggered when Service reject is called with error and params as parameters.

onBefore

  • Type: (params: P[]) => void

  • Details:

    It is triggered before the Service request with params as a parameter.

onAfter

  • Type: (params: P[]) => void

  • Details:

    It is triggered after the Service request is completed with params as a parameter.

Last Updated: 7/6/2023, 3:23:08 AM
Contributors: John