### Install VueRequest via NPM/YARN/PNPM Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/gettingStarted.html Install VueRequest using your preferred package manager. ```bash npm install vue-request # or yarn add vue-request # or pnpm install vue-request ``` -------------------------------- ### Custom Service with Axios Example Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/migration.html Shows how to define a custom service function using Axios to fetch user data. This replaces the previous support for string or object services. ```javascript const getUser = userName => { return axios.get('api/user', { params: { name: userName, }, }); }; useRequest(getUser, options); ``` -------------------------------- ### Basic VueRequest Usage Example Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/gettingStarted.html Demonstrates how to use the `useRequest` hook to fetch data, manage loading states, and handle errors in a Vue.js component. ```vue ``` -------------------------------- ### Custom Service with Async/Await Example Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/migration.html Illustrates defining a custom service function that returns a Promise, handling data processing within the service itself. This is an alternative to the removed `formatResult` option. ```javascript const getUser = async () => { const results = await axios.get('api/user'); // Process the final data here return results.data; }; ``` -------------------------------- ### Custom CacheKey Function Example Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/migration.html Demonstrates how to use a function for cacheKey to dynamically generate cache keys based on request parameters. Handles initialization where params might be undefined. ```javascript useRequest(getUser,{ cacheKey: (params?:P):string => { // Initialize when params is undefined, manually return an empty string if(params){ return `user-key-${params[0].name}` } return '' } }) ``` -------------------------------- ### Basic Usage of useLoadMore Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html Demonstrates the basic setup for the `useLoadMore` hook. The `Service` function must return data with a `list` array. This is the primary way to integrate the load more functionality. ```typescript const { ...ReturnValues } = useLoadMore(Service, Options); ``` -------------------------------- ### Configure with useRequestProvider Hook Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/globalOptions.html Use the `useRequestProvider` hook within a component's setup to apply configurations specifically to that component and its descendants. This allows for more granular control than `setGlobalOptions`. ```javascript import { defineComponent } from 'vue'; import { useRequestProvider } from 'vue-request'; // ... export default defineComponent({ name: 'App', setup() { useRequestProvider({ manual: true, // ... }); return {}; }, }); ``` -------------------------------- ### Fetching User Data with Axios Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/dataFetching.html Example of using `useRequest` with `axios` to fetch user data. The `getUser` function returns an axios Promise. `defaultParams` are provided for the initial request, and `run` can be used to trigger subsequent requests. ```javascript import { useRequest } from 'vue-request'; import axios from 'axios'; const getUser = userName => { return axios.get('api/user', { params: { name: userName, }, }); }; const { data, run } = useRequest(getUser, { defaultParams: ['马冬梅'], }); // ... run('张三'); ``` -------------------------------- ### Redirect after delay Source: https://github.com/attojs/vue-request-docs-zh/blob/master/index.html This JavaScript snippet demonstrates how to redirect the user to a new URL after a specified delay. It's useful for handling deprecated domains or guiding users to updated content. ```javascript setTimeout(function() { window.location.href = "https://www.attojs.com"; }, 3000); ``` -------------------------------- ### 手动模式下的 ready 函数 Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/ready.html 当 `manual` 为 `true` 时,`ready` 可以是一个返回布尔值的函数。只有当该函数返回 `true` 时,请求才会被允许发起。 ```javascript const props = defineProps({ ready: Boolean, }); useRequest(getUser, { ready: () => props.ready, }); ``` -------------------------------- ### ready Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html Controls whether the request is ready to be executed. Defaults to false. ```APIDOC ## ready ### Description Indicates if the request is ready to be executed. This is a reactive property. ### Type `Ref` ### Default Value `false` ``` -------------------------------- ### Setting Default Params with useRequest Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html Demonstrates how to set default parameters for a request using the `defaultParams` option. When `run` is called without arguments, these defaults are used. Subsequent calls to `run` with arguments will update the `params` ref. ```javascript function getUser(name, age) { return axios.get('api/user', { params: { name: name, age: age, }, }); } const { params, run } = useRequest(getUser, { defaultParams: ['John', 18], }); // 默认请求时,如果存在 defaultParams, 则 params.value 将会等于 defaultParams,否则为空数组 // 当 run 传入参数时,此时的参数将会同步到 params 里面 run('Benny', 18); // params.value 等于 ['Benny', 18] ``` -------------------------------- ### Options Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html Configuration options for managing request behavior, including loading states, polling, debouncing, and throttling. ```APIDOC ## Options ### loadingDelay * **Type:** `number | Ref` * **Default:** `0` * **Description:** Delays the time until `loading` becomes `true`, effectively preventing flickering. Useful for preventing loading state flickering. * **Reference:** [Loading State](/guide/documentation/loadingDelay.html#loadingdelay) ### loadingKeep * **Type:** `number | Ref` * **Default:** `0` * **Description:** Keeps the loading animation displayed for a certain duration. * **Reference:** [Loading State](/guide/documentation/loadingDelay.html#loadingkeep) ### pollingInterval * **Type:** `number | Ref` * **Default:** `undefined` * **Description:** Enables polling mode by setting the polling interval in milliseconds, periodically triggering requests. Polling can be started/stopped using `run`/`cancel`. When `manual` is `true`, a manual `run` execution is required to start polling. The interval value must be greater than `0` to take effect. * **Reference:** [Polling](/guide/documentation/polling.html) ### pollingWhenHidden * **Type:** `boolean` * **Default:** `false` * **Description:** When `pollingInterval` is greater than `0`, this option controls whether polling continues when the screen is hidden. If `true`, polling continues even when the screen is not visible. * **Reference:** [Polling When Screen is Hidden](/guide/documentation/polling.html#%E5%B1%8F%E5%B9%95%E4%B8%8D%E5%8F%AF%E8%A7%81%E6%97%B6%E8%BD%AE%E8%AF%A2) ### pollingWhenOffline * **Type:** `boolean` * **Default:** `false` * **Description:** When `pollingInterval` is greater than `0`, this option controls whether polling continues when the network is offline. If `true`, polling continues even when the network is unavailable. * **Reference:** [Polling When Offline](/guide/documentation/polling.html#%E7%BD%91%E7%BB%9C%E7%A6%BB%E7%BA%BF%E6%97%B6%E8%BD%AE%E8%AF%A2) ### debounceInterval * **Type:** `number | Ref` * **Default:** `undefined` * **Description:** Enables debouncing mode by setting the delay in milliseconds. If requests are triggered frequently, they will be handled using a debouncing strategy. * **Reference:** [Debounce](/guide/documentation/debounce.html) ### debounceOptions * **Type:** `DebounceOptions | Reactive` * **Default:** `{ leading: false, maxWait: undefined, trailing: true }` * **Description:** Options for debouncing: `leading` (boolean) specifies calling before the delay starts; `maxWait` (number) sets the maximum delay for the request method; `trailing` (boolean) specifies calling after the delay ends. ### throttleInterval * **Type:** `number | Ref` * **Default:** `undefined` * **Description:** Enables throttling mode by setting the throttle interval in milliseconds. If requests are triggered frequently, they will be handled using a throttling strategy. * **Reference:** [Throttle](/guide/documentation/throttle.html) ### throttleOptions * **Type:** `ThrottleOptions | Reactive` * **Default:** `{ leading: true, trailing: true }` * **Description:** Options for throttling: `leading` (boolean) specifies calling before the throttle starts; `trailing` (boolean) specifies calling after the throttle ends. ### refreshOnWindowFocus * **Type:** `boolean | Ref` * **Default:** `false` * **Description:** When set to `true`, re-requests will be initiated when the browser window triggers `focus` or `visibilitychange` events. * **Reference:** [Re-request on Focus](/guide/documentation/refreshOnWindowFocus.html) ### refocusTimespan * **Type:** `number | Ref` * **Default:** `5000` * **Description:** When `refreshOnWindowFocus` is `true`, this option sets the interval in milliseconds to limit the execution interval of `refresh`. Defaults to 5000ms. * **Reference:** [Re-focus Timespan](/guide/documentation/refreshOnWindowFocus.html#%E9%87%8D%E6%96%B0%E8%81%9A%E7%84%A6%E9%97%B4%E9%9A%94%E6%97%B6%E9%97%B4) ``` -------------------------------- ### manual Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html When set to true, requests are not triggered automatically. Instead, you must manually initiate them using `run` or `runAsync`. ```APIDOC ## manual ### Description When set to true, requests are not triggered automatically. Instead, you must manually initiate them using `run` or `runAsync`. ### Type `boolean` ### Default Value `false` ``` -------------------------------- ### ready Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html Requests are only sent when `ready` evaluates to `true`. In automatic mode (`manual=false`), a request is triggered whenever `ready` changes from `false` to `true`, using `options.defaultParams`. In manual mode (`manual=true`), requests cannot be initiated if `ready` is `false`. ```APIDOC ## ready ### Description Requests are only sent when `ready` evaluates to `true`. In automatic mode (`manual=false`), a request is triggered whenever `ready` changes from `false` to `true`, using `options.defaultParams`. In manual mode (`manual=true`), requests cannot be initiated if `ready` is `false`. ### Type `Ref | () => boolean` ### Default Value `true` ``` -------------------------------- ### initialData Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html Provides the default data for a request before any data is fetched. ```APIDOC ## initialData ### Description Provides the default data for a request before any data is fetched. ### Type `R` ### Default Value `undefined` ``` -------------------------------- ### onBefore Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html Callback function executed before the service is invoked. ```APIDOC ## onBefore ### Description Callback function that is triggered before the service is executed. ### Type `() => void` ``` -------------------------------- ### onBefore Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html A callback function that is executed immediately before the Service initiates a request. It receives the parameters that will be used for the request. ```APIDOC ## onBefore ### Description A callback function that is executed immediately before the Service initiates a request. It receives the parameters that will be used for the request. ### Type `(params: P[]) => void` ``` -------------------------------- ### Service Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html Used to initiate requests for fetching resources. It must be a function that returns a Promise. Third-party request libraries like axios can be used to generate this Promise function. ```APIDOC ## Service ### Description Used to initiate requests for fetching resources. It must be a function that returns a Promise. ### Type `(...params: P[]) => Promise` ### Details `Service` must be a function that returns a `Promise`. You can use third-party request libraries (like `axios`) to help you generate a `Promise` function for initiating resource requests. ```javascript import { useRequest } from 'vue-request'; import axios from 'axios'; const getUser = () => { return axios.get('api/user'); }; const { data } = useRequest(getUser); ``` ### Reference [Data Fetching](/guide/documentation/dataFetching.html) ``` -------------------------------- ### Pagination Extension Options Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/global-options.html Configuration options specific to the pagination extension of VueRequest. ```APIDOC ## Pagination Extension Options Options for the pagination extension: * **pagination**: Configuration object for the pagination feature. See [API Reference for Pagination](/api/pagination.html#pagination) for details. ``` -------------------------------- ### Use Pagination Hook Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/pagination.html This is the primary hook for using the pagination extension. It returns values and methods to manage pagination state. ```javascript const { ...ReturnValues } = usePagination(Service, Options); ``` -------------------------------- ### Public Options Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/global-options.html These are the general configuration options that can be set globally to affect the behavior of VueRequest across your application. ```APIDOC ## Public Options These options can be configured globally: * **loadingDelay**: Controls the delay before showing the loading state. * **pollingInterval**: Sets the interval for polling requests. * **pollingWhenHidden**: Determines if polling should continue when the window is hidden. * **pollingWhenOffline**: Determines if polling should continue when the network is offline. * **debounceInterval**: Sets the interval for debouncing requests. * **debounceOptions**: Configuration options for debouncing. * **throttleInterval**: Sets the interval for throttling requests. * **throttleOptions**: Configuration options for throttling. * **refreshOnWindowFocus**: Enables refreshing requests when the window regains focus. * **refocusTimespan**: Sets the time span for refocusing to trigger a refresh. * **cacheTime**: The duration for which cached data remains valid. * **staleTime**: The duration for which data is considered stale but still usable. * **manual**: If true, requests will not be executed automatically. * **errorRetryCount**: The number of times to retry a failed request. * **errorRetryInterval**: The interval between retrying failed requests. ``` -------------------------------- ### onAfter Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html Callback function executed after the service has finished execution. ```APIDOC ## onAfter ### Description Callback function that is triggered after the service has completed its execution. ### Type `() => void` ``` -------------------------------- ### onSuccess Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html Callback function executed when the service resolves successfully, receiving the data. ```APIDOC ## onSuccess ### Description Callback function executed when the service resolves successfully. It receives the fetched data as an argument. ### Type `(data: DataType) => void` ``` -------------------------------- ### Manual Triggering with Manual Option Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/loadMore.html When the `manual` option is set to `true`, requests are not automatically initiated. You must manually call `loadMore` or `loadMoreAsync` to trigger the data fetching process. ```javascript const { loadMore, loadMoreAsync } = useLoadMore(service, { manual: true, }); // To trigger loading more: loadMore(); // Or to handle promise manually: loadMoreAsync().then(data => { /* ... */ }); ``` -------------------------------- ### Basic useRequest Hook Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/dataFetching.html The most basic API for data fetching. `Service` must be a function returning a Promise. The resolved value goes to `data`, and the rejected value goes to `error`. Function arguments are passed as `params`. ```javascript const { data, error } = useRequest(Service, options); ``` -------------------------------- ### Include VueRequest via CDN Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/gettingStarted.html Include VueRequest in your HTML file using a CDN link for direct use. It will be available as `window.VueRequest`. ```html ``` -------------------------------- ### 使用 watch 监听值变化并刷新数据 Source: https://github.com/attojs/vue-request-docs-zh/blob/master/guide/documentation/refreshDeps.html 当需要动态监听某些值变化并触发数据请求时,可以使用 watch 结合 refresh 函数。此方法适用于需要复杂监听逻辑的场景。 ```javascript import { ref, watch, reactive } from 'vue'; import { useRequest } from 'vue-request'; const someRef = ref(0); const someReactive = reactive({ count: 0, }); const { data, refresh } = useRequest(getUser); watch([someRef, () => someReactive.count], refresh); ``` -------------------------------- ### defaultParams Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html If `manual` is set to `false`, these parameters will be used when automatically executing requests. ```APIDOC ## defaultParams ### Description If `manual` is set to `false`, these parameters will be used when automatically executing requests. ### Type `P[]` ### Default Value `[]` ``` -------------------------------- ### Return Values Source: https://github.com/attojs/vue-request-docs-zh/blob/master/api/index.html Details the reactive state and control functions returned by the `useRequest` hook. ```APIDOC ## Return Values ### data * **Type:** `shallowRef` * **Default:** `undefined` * **Description:** Holds the data returned by the service. It's a shallow reactive reference. ### loading * **Type:** `Ref` * **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.