Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

vue-request

attojs14kMIT2.0.4TypeScript support: included

This is a library that can easily help you manage request states, supporting common features such as SWR, polling, error retry, caching, and pagination, etc.

vue, vue3, vue2, swr, request, http, fetch, composition-api, vue-demi, axios, vue-request, vue request

readme

English | 简体中文

VueRequest logo

VueRequest

⚡️ 这是一个能够轻松帮助你管理请求状态的库,支持 SWR、轮询、错误重试、缓存、分页等常用功能。

Coverage Status Size Version Languages License Star Download

为什么选择 VueRequest

在以往的业务项目中,我们经常会被 loading 状态的管理、请求的节流防抖、接口数据的缓存、分页等重复的功能实现所困扰。每次开启一个新项目都需要重新实现一遍,这是一项重复的工作,还需要确保团队的一致性。

VueRequest 的目的是为开发人员提供一种方便、快速的方式来管理 API 状态。通过简单的配置,可以省去那些繁琐的任务,专注于业务核心的开发。

特性

  • 🌈  兼容 Vue 2 & 3
  • 🚀  所有数据都具有响应式
  • 🔄  轮询请求
  • 🤖  自动处理错误重试
  • 🗄  内置请求缓存
  • 💧  节流请求与防抖请求
  • 🎯  聚焦页面时自动重新请求
  • ⚙️  强大的分页扩展以及加载更多扩展
  • 📠  完全使用 Typescript 编写,具有强大的类型提示
  • ⚡️  兼容 Vite
  • 🍃  轻量化
  • 📦  开箱即用

文档

安装

你可以通过 NPMYARN 或者通过 <script> 的方式引入 unpkg.com 上的包。

NPM

npm install vue-request
# or
yarn add vue-request
# or
pnpm install vue-request

CDN

对于生产环境,我们推荐链接到一个明确的版本号和构建文件,以避免新版本造成的不可预期的破坏。

<script src="https://unpkg.com/vue-request/dist/vue-request.min.js"></script>

一旦你在页面中添加了它,你就可以在 window.VueRequest 中访问我们导出的方法。

示例

<template>
  <div>
    <div v-if="loading">loading...</div>
    <div v-if="error">failed to fetch</div>
    <div v-if="data">Hey! {{ data }}</div>
  </div>
</template>

<script lang="ts" setup>
const { data, loading, error } = useRequest(service);
</script>

在这个例子中,useRequest 接收了一个 service 函数。service是一个异步的请求函数,换句话说,你可以使用 axios 来获取数据,然后返回一个 Promise。更具体的说明可以在文档中查看。

useRequest 函数还会返回三个值:dataloadingerror。当请求还未完成时,data 的值为 undefined,同时 loading 的值会被设置为 true。当请求完成后,dataerror 的值将根据请求结果进行设置,并且页面也会相应地进行渲染。这是因为 dataloadingerror 是 Vue 中的响应式引用(Refs),它们的值会根据请求状态和结果进行修改。

一些很酷的特性

VueRequest 提供了很多特性,如:错误重试、缓存、分页、节流、防抖等等。这里列举两个比较酷的特性:

1.聚焦页面时自动重新请求

有时,你需要确保多个浏览器窗口之间的数据保持一致性;或者在用户电脑从休眠状态中恢复并重新激活时,需要将页面的数据同步到最新状态。使用 refreshOnWindowFocus 可以帮助你节省很多逻辑代码。点击这里直达文档

const { data, error, run } = useRequest(getUserInfo, {
  refreshOnWindowFocus: true,
  refocusTimespan: 1000, // 请求间隔时间
});

vue-request

2.轮询数据

有时候,你需要确保多个设备之间的数据同步更新。这时候可以使用我们提供的 pollingInterval 定期重新请求接口,以确保多个设备之间的数据一致性。当用户修改数据时,两个窗口将会实时同步更新。点击这里直达文档

const { data, error, run } = useRequest(getUserInfo, {
  pollingInterval: 1000, // 请求间隔时间
});

vue-request

致谢

感谢他们为我们提供了灵感

License

MIT License © 2020-present AttoJS

changelog

Changelog

All notable changes to this project will be documented in this file. See standard-version for commit guidelines.

2.0.4 (2023-10-16)

Refactor

2.0.3 (2023-06-13)

Refactor

2.0.2 (2023-06-02)

Refactor

2.0.1 (2023-06-01)

Changelog

  • Use vue-demi to be compatible with Vue 2 #38
  • Added custom cache getCache, setCache, and clearCache.
  • When caching is enabled, requests with the same cacheKey will be cached and reused.
  • Added runAsync and refreshAsync, which return a Promise.
  • Added definePlugin to extend the functionality of useRequest through plugins.
  • In throttle/debounce mode, runAsync can be used to return a normal Promise.
  • Added useRequestProvider hooks to inject options configuration.
  • Added refreshDepsAction option to customize the behavior after refreshDeps is triggered.
  • refreshDepsAction will also be triggered by changes in refreshDeps when manual=true.
  • Added loadingKeep.
  • Removed the integrated request library and service no longer supports strings or objects. Migration Guide
  • Removed formatResult. Migration Guide
  • Removed queryKey, i.e., parallel mode is removed Migration Guide
  • run no longer returns a Promise Migration Guide
  • When a request fails, data is no longer cleared #82
  • Modified the logic of ready Migration Guide
  • ready now supports passing a function that returns a Boolean value #166
  • data and error changed to shallowRef
  • usePagination removed reload method and reloading. If needed, they can be implemented separately.
  • Removed RequestConfig component Migration Guide
  • Refactored useLoadMore, see details for specific API API Description
  • cacheKey can now be passed a function: cacheKey: (params?: P) => string
    useRequest(getUser, {
      cacheKey: (params?: P): string => {
        // When initialized, `params` will be undefined, so we need to manually check and return an empty string
        if (params) {
          return `user-key-${params[0].name}`;
        }
        return '';
      },
    });
  • Some options support reactivity, as shown below:

    type ReactivityOptions = {
      loadingDelay: number | Ref<number>;
      loadingKeep: number | Ref<number>;
      pollingInterval: number | Ref<number>;
      debounceInterval: number | Ref<number>;
      debounceOptions: DebounceOptions | Reactive<DebounceOptions>;
      throttleInterval: number | Ref<number>;
      throttleOptions: ThrottleOptions | Reactive<ThrottleOptions>;
      refreshOnWindowFocus: boolean | Ref<boolean>;
      refocusTimespan: number | Ref<number>;
      errorRetryCount: number | Ref<number>;
      errorRetryInterval: number | Ref<number>;
    };
  • refreshDeps now supports passing a function that returns a value, a ref, a reactive object, or an array of any of these types. #166

Migration Guide

  1. service no longer supports strings or objects. Users are expected to wrap their requests using other third-party libraries (such as axios) and provide a Promise as the service function.

    const getUser = userName => {
      return axios.get('api/user', {
        params: {
          name: userName,
        },
      });
    };
    useRequest(getUser, options);
  2. formatResult has been removed. Users are expected to format the final data in their service function.

    const getUser = async () => {
      const results = await axios.get('api/user');
      // Format the final data here
      return results.data;
    };
  3. queryKey has been removed, which means parallel mode is no longer supported. Users are expected to encapsulate each request action and UI into a component instead of putting all requests in the parent component.

  4. Changes to the ready logic

    • When manual=false, every time ready changes from false to true, a request will be automatically triggered with the options.defaultParams parameter.
    • When manual=true, a request cannot be made as long as ready is false.
  5. run no longer returns a Promise. Use runAsync instead of the original run function.

  6. Users can wrap useRequest with useRequestProvider themselves.

useLoadMore API

Options

Name Description Type
manual When set to true, you need to manually trigger loadMore or loadMoreAsync to make a request. The default value is false. boolean
ready When manual=false, every time ready changes from false to true, refresh will be automatically triggered. When manual=true, a request cannot be made as long as ready is false. Ref<boolean> | () => boolean
refreshDeps Automatically trigger refresh when changed. If refreshDepsAction is set, refreshDepsAction will be triggered. WatchSource<any> | WatchSource<any>[]
refreshDepsAction Triggered when refreshDeps changes. () => void
debounceInterval Process the request with a debounce strategy. number | Ref<number>
debounceOptions Debounce parameters. {leading: false, maxWait: undefined, trailing: true}
throttleInterval Process the request with a throttle strategy. number | Ref<number>
throttleOptions Throttle parameters. {leading: false, trailing: true}
errorRetryCount The number of error retries when an error occurs. number | Ref<number>
errorRetryInterval The interval between error retries when an error occurs. number | Ref<number>
isNoMore Determines whether there is more data. (data?: R) => boolean
onBefore Triggered before service is executed. () => void
onAfter Triggered when service is completed. () => void
onSuccess Triggered when service is resolved. (data: R) => void
onError Triggered when service is rejected. (error: Error) => void

Result

Name Description Type
data The data returned by service, which must include an array list, of type { list: any[], ...other }. Ref<R>
dataList The list array of data. Ref<R['list']>
loading Whether a request is in progress. Ref<boolean>
loadingMore Whether more data is being loaded. Ref<boolean>
noMore Whether there is more data, which needs to be used with options.isNoMore. Ref<boolean>
error The error returned by service. Error
loadMore Load more data, automatically capture exceptions, and handle them through options.onError. () => void
loadMoreAsync Load more data, return Promise, and handle errors on your own. () => Promise<R>
refresh Refresh and load the first page of data, automatically capture exceptions, and handle them through options.onError. () => void
refreshAsync Refresh and load the first page of data, return Promise, and handle errors on your own. () => Promise<R>
mutate Directly modify the result of data. (arg: (oldData: R) => R) => void | (newData: R) => void
cancel Cancel the request. () => void

1.2.4 (2022-01-21)

Refactor

  • replacing IIFE with UMD modules (2f05be8)

1.2.3 (2021-10-12)

Bug Fixes

1.2.2 (2021-10-06)

Bug Fixes

  • Fix nullish operator is not transform

1.2.1 (2021-10-06)

Features

  • core: add throttle and debounce options #63 (decbbd3)

1.2.0 (2021-05-22)

Features

  • usePagination: add changePagination() to modify both current and pageSize #43 (c3822f0)
  • add onBefore() and onAfter() hooks #42 (135e76f)
  • add reloading to record the loading status of reload() #41 (5034f2c)

Performance Improvements

⚠ BREAKING CHANGES

1.1.1 (2021-04-28)

Bug Fixes

  • usePagination: defaultParams.current and defaultParams.pageSize should work if manual: true (3ca5fd7), closes #40

1.1.0 (2021-04-19)

Features

  • useLoadMore: refactor refresh and cancel of useLoadMore, add refreshing #36 (7c34351)

Bug Fixes

  • root level refresh, mutate, cancel not work with queryKey #37 (66b3198)

⚠ BREAKING CHANGES

  • useLoadMore: remove mutate of useLoadMore (b935bcd)

1.0.5 (2021-03-22)

Bug Fixes

1.0.4 (2021-03-08)

Bug Fixes

1.0.3 (2021-03-06)

Bug Fixes

  • concurrent request should have independent events (7511720)

Features

  • usePagination and useLoadMore support global config (8cceb1e)
  • usePagination: add reload function to reset paging info (def45e3)
  • useRequest: add reload function to clear the queries list (b64216b)

1.0.0-beta.11 (2021-03-03)

Features

1.0.0-beta.10 (2021-03-02)

⚠ BREAKING CHANGES

  • queries changed from shallowReactive to reactive (8f940a4)

1.0.0-beta.9 (2021-02-26)

⚠ BREAKING CHANGES

  • usePagination: does not support concurrent request (2c083ef)

Refactor

  • usePagination: current and pageSize can modify and can trigger request, means you can directly use v-model to bind them (ea5a238)

1.0.0-beta.8 (2021-02-24)

Features

1.0.0-beta.7 (2021-01-11)

Feature

  • add back off algorithm to errorRetryInterval (#19) 13ce153

1.0.0-beta.6 (2020-12-31)

Refactor

  • add isServer to be compatible with node env 4f1c797
  • modify the default value of cacheTime to 10 minutes a56ecb0

1.0.0-beta.5 (2020-12-14)

Bug Fixes

1.0.0-beta.4 (2020-12-07)