`
* **Default:** `false`
* **Description:** Indicates whether a request is currently in progress. It's a reactive boolean.
### params
* **Type:** `Ref`
* **Default:** `[]`
* **Description:** Stores the parameters currently used for the request. It's a reactive array of parameters.
* **Example:**
```javascript
function getUser(name, age) {
return axios.get('api/user', {
params: {
name: name,
age: age,
},
});
}
const { params, run } = useRequest(getUser, {
defaultParams: ['John', 18],
});
// When the request is made with defaultParams, params.value will be ['John', 18].
// When run is called with arguments, they update params.
run('Benny', 18); // params.value will be ['Benny', 18]
```
### error
* **Type:** `shallowRef`
* **Default:** `undefined`
* **Description:** Captures any error thrown during the request execution.
### run
* **Type:** `(...params: P[]) => void`
* **Description:** Manually triggers the service request with the provided parameters. It automatically handles errors using `options.onError`.
### runAsync
* **Type:** `(...params: P[]) => Promise`
* **Description:** Similar to `run`, but returns a `Promise` that resolves with the service result. You need to handle exceptions manually.
### cancel
* **Type:** `() => void`
* **Description:** Manually cancels the current request. This stops the assignment of data to `data` and resets `loading` to `false`, but does not stop already initiated network requests.
* **Note:** This also stops polling if it's active.
### refresh
* **Type:** `() => void`
* **Description:** Re-executes the service request using the previously used parameters by calling `run`.
### refreshAsync
* **Type:** `() => Promise`
* **Description:** Re-executes the service request using the previously used parameters by calling `runAsync`.
```
--------------------------------
### Import Pagination Hook
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/pagination.html
Import the usePagination hook from the vue-request library to enable pagination functionality.
```javascript
import { usePagination } from 'vue-request';
```
--------------------------------
### throttleOptions
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html
Options for throttling the request.
```APIDOC
## throttleOptions
### Description
Configuration options for the throttle functionality.
### Type
`ThrottleOptions | Reactive`
```
--------------------------------
### 使用 refreshDeps 语法糖
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/refreshDeps.html
refreshDeps 是 watch 监听的语法糖,用于简化依赖值变化时触发请求的逻辑。它提供了与直接使用 watch 相同的效果,但代码更简洁。
```javascript
import { ref, watch, reactive } from 'vue';
import { useRequest } from 'vue-request';
const someRef = ref(0);
const { data, run } = useRequest(getUser, {
refreshDeps: someRef,
refreshDepsAction: () => {
run(1);
},
});
```
--------------------------------
### onAfter
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html
A callback function that is executed after the Service has completed its request, regardless of whether it succeeded or failed. It receives the parameters used for the request.
```APIDOC
## onAfter
### Description
A callback function that is executed after the Service has completed its request, regardless of whether it succeeded or failed. It receives the parameters used for the request.
### Type
`(params: P[]) => void`
```
--------------------------------
### onSuccess
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html
A callback function that is executed when the Service resolves successfully. It receives the fetched data and the parameters used for the request.
```APIDOC
## onSuccess
### Description
A callback function that is executed when the Service resolves successfully. It receives the fetched data and the parameters used for the request.
### Type
`(data: R, params: P[]) => void`
```
--------------------------------
### refreshDeps
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html
An array of dependencies. If any dependency in this array changes and `refreshDepsAction` is not set, the `refresh` function will be triggered, effectively re-executing the request. This is essentially a wrapper around Vue's `watch`.
```APIDOC
## refreshDeps
### Description
An array of dependencies. If any dependency in this array changes and `refreshDepsAction` is not set, the `refresh` function will be triggered, effectively re-executing the request. This is essentially a wrapper around Vue's `watch`.
### Type
`WatchSource | WatchSource[]`
### Default Value
`[]`
```
--------------------------------
### Polling with Interval and Continue When Hidden
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/polling.html
Configure polling to occur every 1000ms and continue even when the screen is not visible. Requires importing useRequest from vue-request.
```javascript
import { useRequest } from 'vue-request';
const { data, loading } = useRequest(getTodo, {
pollingInterval: 1000,
pollingWhenHidden: true,
});
```
--------------------------------
### useLoadMore Hook
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html
The `useLoadMore` hook is used to implement the "load more" functionality. It takes a service function and options as arguments and returns various values to manage the loading state and data.
```APIDOC
## useLoadMore Hook
### Description
This hook provides functionality for implementing "load more" or infinite scrolling features in your Vue application.
### Usage
```javascript
const { ...ReturnValues } = useLoadMore(Service, Options);
```
### Service Function
* **Type:** `(data?: DataType) => Promise`
* **Details:**
* The `Service` function must return data that includes a `list` array, conforming to the structure `{ list: any[], ...other }`.
* The input parameter `data` to the `Service` function is the aggregated data from previous requests.
### Return Values
* **data** (`shallowRef`): The data returned by the `Service`. It must contain a `list` array.
* **dataList** (`Ref`): The `list` array extracted from the `data`.
* **error** (`shallowRef`): Any error encountered during the service request.
* **loading** (`Ref`): Indicates if a request is currently in progress.
* **loadingMore** (`Ref`): Indicates if more data is being loaded.
* **noMore** (`Ref`): Indicates if there is no more data available.
* **loadMore** (`() => void`): Function to trigger loading more data. Handles exceptions internally.
* **loadMoreAsync** (`() => Promise`): Similar to `loadMore`, but returns a Promise, requiring manual exception handling.
* **refresh** (`() => void`): Function to reload the first page of data. Handles exceptions internally.
* **refreshAsync** (`() => Promise`): Similar to `refresh`, but returns a Promise, requiring manual exception handling.
* **mutate** (`(arg: (oldData: DataType) => DataType) => void | (newData: DataType) => void`): Function to directly modify the `data`.
* **cancel** (`() => void`): Function to cancel the ongoing request.
### Options
* **isNoMore** (`(data?: DataType) => boolean`): A function to determine if there is more data to load.
* **manual** (`boolean`): If `true`, requests are not triggered automatically and must be initiated manually using `loadMore` or `loadMoreAsync`.
```
--------------------------------
### cacheKey
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html
Defines a cache key for requests. If set, VueRequest caches request data (data, error, params, loading). On component initialization, cached data is returned first, followed by a background request for updated data. This enables SWR capabilities. Changing data for one cacheKey also synchronizes other identical cacheKeys. It also ensures that only one request is made for the same cacheKey at a time, with subsequent requests sharing the same Promise.
```APIDOC
## cacheKey
### Description
Defines a cache key for requests. If set, VueRequest caches request data (data, error, params, loading). On component initialization, cached data is returned first, followed by a background request for updated data. This enables SWR capabilities. Changing data for one cacheKey also synchronizes other identical cacheKeys. It also ensures that only one request is made for the same cacheKey at a time, with subsequent requests sharing the same Promise.
### Type
`string | (params?: P) => string`
### Default Value
`undefined`
```
--------------------------------
### Polling with Interval and Continue When Offline
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/polling.html
Configure polling to occur every 1000ms and continue even when the network is offline. Requires importing useRequest from vue-request. Note that VueRequest uses window.ononline to check network status.
```javascript
import { useRequest } from 'vue-request';
const { data, loading } = useRequest(getTodo, {
pollingInterval: 1000,
pollingWhenOffline: true,
});
```
--------------------------------
### Configure Retry Interval
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/errorRetry.html
Use `errorRetryInterval` to set a fixed delay in milliseconds between retries. The default behavior uses a binary exponential backoff algorithm to calculate intervals.
```javascript
import { useRequest } from 'vue-request';
const { data } = useRequest(getUser, {
errorRetryCount: 5, // it will retry 5 times
errorRetryInterval: 3 * 1000, // The retry interval is 3 seconds
});
```
--------------------------------
### refreshDepsAction
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html
A callback function that is executed when any of the dependencies in `refreshDeps` change. This action is also triggered when `manual` is set to `true`.
```APIDOC
## refreshDepsAction
### Description
A callback function that is executed when any of the dependencies in `refreshDeps` change. This action is also triggered when `manual` is set to `true`.
### Type
`() => void`
```
--------------------------------
### debounceOptions
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html
Options for debouncing the request.
```APIDOC
## debounceOptions
### Description
Configuration options for the debounce functionality.
### Type
`DebounceOptions | Reactive`
```
--------------------------------
### Set Refocus Timespan
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/refreshOnWindowFocus.html
Configure `refocusTimespan` to set a minimum interval (in milliseconds) between automatic re-fetches triggered by window focus. This prevents excessive requests in quick succession.
```javascript
const { data } = useRequest(getUser, {
refreshOnWindowFocus: true,
refocusTimespan: 2 * 1000, // 2s
});
```
--------------------------------
### usePagination Hook
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/pagination.html
The usePagination hook provides pagination capabilities. It accepts a service function and options, and returns pagination-related values and methods.
```APIDOC
## usePagination Hook
### Description
Provides pagination capabilities by extending the core VueRequest functionality. It allows for managing current page, page size, total items, and total pages.
### Usage
```javascript
const { ...ReturnValues } = usePagination(Service, Options);
```
### Parameters
#### Service
- **Service** (Function) - The service function to fetch data.
#### Options
- **Options** (Object) - Configuration options for pagination.
- **pagination** (Object) - Configuration for pagination behavior.
- **currentKey** (string) - Optional. The key for the current page parameter in the request. Defaults to 'current'.
- **pageSizeKey** (string) - Optional. The key for the page size parameter in the request. Defaults to 'pageSize'.
- **totalKey** (string) - Optional. The path to the total number of items in the response data. Defaults to 'total'.
- **totalPageKey** (string) - Optional. The path to the total number of pages in the response data. Defaults to 'totalPage'.
### Return Values
- **current** (Ref) - The current page number. Defaults to 1.
- **pageSize** (Ref) - The number of items per page. Defaults to 10.
- **total** (Ref) - The total number of items.
- **totalPage** (Ref) - The total number of pages.
- **changeCurrent** (Function) - A function to change the current page. `(current: number) => void`.
- **changePageSize** (Function) - A function to change the page size. `(pageSize: number) => void`.
- **changePagination** (Function) - A function to change both current page and page size. `(current: number, pageSize: number) => void`.
```
--------------------------------
### Enable Refresh on Window Focus
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/refreshOnWindowFocus.html
Use `refreshOnWindowFocus: true` to automatically re-fetch data when the window is refocused. This is useful for maintaining data consistency across tabs or after system sleep.
```javascript
const { data } = useRequest(getUser, {
refreshOnWindowFocus: true,
});
```
--------------------------------
### onError
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html
Callback function executed when the service rejects, receiving the error object.
```APIDOC
## onError
### Description
Callback function executed when the service rejects. It receives the error object as an argument.
### Type
`(error: Error) => void`
```
--------------------------------
### Importing useLoadMore Hook
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/loadMore.html
Import the `useLoadMore` hook from the `vue-request` library to enable the load more functionality.
```javascript
import { useLoadMore } from 'vue-request';
```
--------------------------------
### Set Global Options via CDN
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/globalOptions.html
When using VueRequest via a CDN, you can set global options by calling `setGlobalOptions` on the `VueRequest` object available in the global scope.
```javascript
```
--------------------------------
### Set Global Options in main.ts
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/globalOptions.html
Use `setGlobalOptions` to configure options that will be applied to all VueRequest components in your project. This method is typically called in your main application entry file.
```javascript
// main.ts
import { setGlobalOptions } from 'vue-request';
// ...
setGlobalOptions({
manual: true,
// ...
});
// App.tsx
const { data: user } = useRequest(getUser);
const { data: job } = useRequest(getJob, { manual: false }); // 覆盖全局配置
```
--------------------------------
### refreshDeps
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html
Dependencies that trigger a refresh of the request when they change. Defaults to an empty array.
```APIDOC
## refreshDeps
### Description
An array of dependencies that, when changed, will trigger a refresh of the request.
### Type
`WatchSource[]`
### Default Value
`[]`
```
--------------------------------
### Define a Service Function with Axios
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html
Define a service function that returns a Promise, typically using a third-party library like axios for making API requests. This function will be passed to useRequest.
```javascript
import { useRequest } from 'vue-request';
import axios from 'axios';
const getUser = () => {
return axios.get('api/user');
};
const { data } = useRequest(getUser);
```
--------------------------------
### setCache
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html
Allows custom setting of cache data. This function takes a cache key and cache data (including data, params, and timestamp) as arguments.
```APIDOC
## setCache
### Description
Allows custom setting of cache data. This function takes a cache key and cache data (including data, params, and timestamp) as arguments.
### Type
`(cacheKey: string, cacheData: CacheData) => void`
Where `CacheData` is defined as:
```typescript
type CacheData = {
data: R;
params: P;
time: number;
};
```
```
--------------------------------
### Configure Retry Count
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/errorRetry.html
Set the `errorRetryCount` option to specify how many times a failed request should be retried. This is useful for transient errors that might resolve quickly.
```javascript
import { useRequest } from 'vue-request';
const { data } = useRequest(getUser, {
errorRetryCount: 5, // it will retry 5 times
});
```
--------------------------------
### getCache
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html
Enables custom retrieval of cache data. This function takes a cache key and returns the corresponding cache data, which includes the data, parameters, and timestamp.
```APIDOC
## getCache
### Description
Enables custom retrieval of cache data. This function takes a cache key and returns the corresponding cache data, which includes the data, parameters, and timestamp.
### Type
`(cacheKey: string) => CacheData`
Where `CacheData` is defined as:
```typescript
type CacheData = {
data: R;
params: P;
time: number;
};
```
```
--------------------------------
### throttleInterval
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html
The interval in milliseconds for throttling the request. Defaults to undefined.
```APIDOC
## throttleInterval
### Description
Sets the throttle interval in milliseconds for the request. This is a reactive property.
### Type
`number | Ref`
### Default Value
`undefined`
```
--------------------------------
### useRequest Hook
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html
The core hook for managing asynchronous requests. It takes a service function and options, returning reactive state and control functions.
```APIDOC
## useRequest Hook
### Description
The `useRequest` hook is the primary interface for managing asynchronous data fetching and state in Vue applications. It accepts a service function and an options object to configure request behavior, caching, and more.
### Usage
```javascript
const { data, loading, params, error, run, runAsync, cancel, refresh, refreshAsync, mutate } = useRequest(Service, Options);
```
### Generics
* `R`: Type of the data returned by the service.
* `P`: Type of the parameters accepted by the service. Constrained by `unknown[]`.
```
--------------------------------
### errorRetryInterval
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html
Configures the interval between error retries. By default, VueRequest uses exponential backoff to calculate the interval. This option allows overriding that behavior.
```APIDOC
## errorRetryInterval
### Description
Configures the interval between error retries. By default, VueRequest uses exponential backoff to calculate the interval. This option allows overriding that behavior.
### Type
`number | Ref`
### Default Value
`0`
```
--------------------------------
### useRequest Hook Signature
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html
The basic signature for the useRequest hook, showing its generic types for response (R) and parameters (P).
```typescript
const { ...ReturnValues } = useRequest(Service, Options);
```
--------------------------------
### cacheTime
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html
Sets the expiration time for cached data when caching is enabled. After the cache expires, it will be deleted. The default is 600,000 milliseconds (10 minutes).
```APIDOC
## cacheTime
### Description
Sets the expiration time for cached data when caching is enabled. After the cache expires, it will be deleted. The default is 600,000 milliseconds (10 minutes).
### Type
`number`
### Default Value
`10 * 60 * 1000`
```
--------------------------------
### debounceInterval
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html
The interval in milliseconds for debouncing the request. Defaults to undefined.
```APIDOC
## debounceInterval
### Description
Sets the debounce interval in milliseconds for the request. This is a reactive property.
### Type
`number | Ref`
### Default Value
`undefined`
```
--------------------------------
### Modify Fetched Data with mutate()
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/mutation.html
Use `mutate()` to directly change the data returned by a request. For simple modifications, consider using `computed` instead.
```javascript
const { data } = useRequest(getUser);
const slogan = computed(() => `有一个 ${data.value} 前来买瓜。`);
```
--------------------------------
### staleTime
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html
Specifies a time duration in milliseconds during which cached data is considered 'fresh' and will not trigger a new request. If set to 0 (default), no data freshness is guaranteed, and a request is made every time. Setting it to -1 means the cache never expires.
```APIDOC
## staleTime
### Description
Specifies a time duration in milliseconds during which cached data is considered 'fresh' and will not trigger a new request. If set to 0 (default), no data freshness is guaranteed, and a request is made every time. Setting it to -1 means the cache never expires.
### Type
`number`
### Default Value
`0`
```
--------------------------------
### Service Function Signature
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html
Defines the expected signature for the `Service` function used with `useLoadMore`. It accepts the integrated data from previous calls and must return a Promise resolving to data containing a `list` array.
```typescript
type DataType = { list: any[]; [key: string]: any };
// Service signature:
(data?: DataType) => Promise
```
--------------------------------
### refreshDepsAction
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html
A function to be called when refreshDeps triggers a refresh.
```APIDOC
## refreshDepsAction
### Description
A callback function that is executed when the `refreshDeps` trigger a refresh action.
### Type
`() => void`
```
--------------------------------
### errorRetryInterval
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html
The interval in milliseconds between retries when an error occurs. Defaults to 0.
```APIDOC
## errorRetryInterval
### Description
Sets the interval in milliseconds between retry attempts when an error occurs. This is a reactive property.
### Type
`number | Ref`
### Default Value
`0`
```
--------------------------------
### errorRetryCount
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html
The number of times to retry the request upon encountering an error. Defaults to 0.
```APIDOC
## errorRetryCount
### Description
Specifies the number of times the request should be retried if an error occurs. This is a reactive property.
### Type
`number | Ref`
### Default Value
`0`
```
--------------------------------
### mutate
Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html
Directly modifies the data result. It accepts a function that receives the old data and returns the new data, or directly accepts the new data.
```APIDOC
## mutate
### Description
Directly modifies the data result.
### Type
`(arg: (oldData: R) => R) => void | (newData: R) => void`
### Reference
[Data Mutation](/guide/documentation/mutation.html)
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.