Public API

VueRequest usually consists of three parts: Return Values, Service, and Options

const { ...ReturnValues } = useRequest<R, P>(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)

Return Values

data

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

params

  • Type: Ref<P[]>

  • Default: []

    Service request parameters

  • Usage:

    function getUser(name, age) {
      return axios.get('api/user', {
        params: {
          name: name,
          age: age,
        },
      });
    }
    
    const { params, run } = useRequest(getUser, {
      defaultParams: ['John', 18],
    });
    // 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', 18); // params.value is ['Benny', 18]
    

error

  • Type: shallowRef<Error | undefined>

  • Default: undefined

    If an error is thrown internally, it will be received by error and returned.

run

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

    Manually trigger the request of Service

runAsync

  • Type: (...params: P[]) => Promise<R>

    The usage is the same as run, but it returns a Promise, so you need to handle the exception yourself.

cancel

  • Type: () => void

    • Manually cancel the current request.
    • Pause polling.

    Note

    The cancellation mentioned here is not a real stop request but cancels the assignment of data and resets loading to false. The current request will not be interrupted.

refresh

  • Type: () => void

    Use the last params, call run again

refreshAsync

mutate

  • Type: (arg: (oldData: R) => R) => void | (newData: R) => void

    Modify data directly

  • See also: Mutation

Service

For the request. See also Data Fetching

Request Method

  • Type: (...params: P[]) => Promise<R>

  • Details:

    Service must be a function that returns a Promise. You can use third-party request library (such as axios) to help you generate a Promise 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);
    

Options

loadingDelay reactivity

  • Type: number | Ref<number>

  • Default: 0

  • Details:

    By setting the delay in milliseconds, you can delay the time loading becomes true, effectively preventing flicker.

  • See also: Loading State

loadingDelay reactivity

  • Type: number | Ref<number>

  • Default: 0

  • Details:

    Keep loading state for some time.

  • See also: Loading State

pollingInterval reactivity

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

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

pollingWhenHidden

  • Type: boolean

  • Default: false

  • Details:

    It takes effect when pollingInterval is greater than 0. By default, polling will be suspended when the screen is not visible. When set to true, 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 than 0. By default, polling will be suspended when the network is unavailable. When set to true, the polling task will still be executed regularly when the network is not available.

  • See also: PollingWhenOffline

debounceInterval reactivity

  • Type: number | Ref<number>

  • Default: undefined

  • Details:

    Enter the debounce mode by setting the number of milliseconds to delay. At this time, if the request is triggered frequently, the request will be made with the 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): 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 reactivity

  • Type: number | Ref<number>

  • Default: undefined

  • Details:

    Enter the throttling mode by setting the number of milliseconds for throttling. At this time, if the request is triggered frequently, the request will be made with a throttling strategy.

  • See also: Throttle

throttleOptions reactivity

  • Type: ThrottleOptions | Reactive<ThrottleOptions>

    type ThrottleOptions = {
      leading: boolean;
      trailing: boolean;
    };
    
  • 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 reactivity

refocusTimespan reactivity

  • Type: number | Ref<number>

  • Default: 5 * 1000

  • Details:

    When refreshOnWindowFocus is set to true, you can limit the execution interval of refresh by setting the interval in milliseconds. The default is 5000ms.

  • See also: RefocusTimespan

cacheKey

  • Type: string | (params?: P) => 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.
    • Sharing request Promise, only one of the same cacheKey will initiate a request at the same time, and the subsequent ones will share the same request Promise.
  • See also: Cache / Preload

cacheTime

  • Type: number

  • Default: 10* 60 * 1000

  • 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.
  • See also: StaleTime

setCache

  • Type: (cacheKey: string, cacheData: CacheData) => void

    type CacheData = {
      data: R;
      params: P;
      time: number;
    };
    
  • Details:

    Custom set cache

  • 参考: Custom cache

getCache

  • Type: (cacheKey: string) => CacheData
type CacheData = {
  data: R;
  params: P;
  time: number;
};

errorRetryCount reactivity

  • Type: number | Ref<number>

  • Default: 0

  • Details:

    Max error retry count

  • 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, when the run is automatically executed, defaultParams will be used as the request parameter.

ready reactivity

  • Type: Ref<boolean>

  • Default: true

  • Details:

    Only when ready is true 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.
  • See also: Dependent Request

initialData

  • Type: R

  • Default: undefined

  • Details:

    Initialized data.

refreshDeps

  • Type: WatchSource<any>[]

  • Default: []

  • Details:

    When the content of refreshDeps changes, if refreshDepsAction is not set, it will trigger the re-execution of refresh. Its essence is just an encapsulation of watchopen in new window

watch(refreshDeps, refresh);

refreshDepsAction

  • Type: () => void

  • Details:

    Called when the contents of refreshDeps have changed. manual=true is also triggered.

  • See also: refreshDepsAction

onSuccess

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

  • Details:

    Triggered when Service resolve, the parameters are data and params.

onError

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

  • Details:

    Triggered when Service reject, the parameters are error and params.

onBefore

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

  • Details:

    Triggered before Service request, the parameters is params.

onAfter

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

  • Details:

    Triggered after Service request, the parameters is params.

Last Updated: 7/1/2022, 8:28:34 AM
Contributors: John