Skip to content

v2.0.1

Compare
Choose a tag to compare
@John60676 John60676 released this 02 Jun 06:59

变更列表

  • 使用 vue-demi 兼容 vue2 #38

  • 新增自定义缓存 getCachesetCacheclearCache

  • 开启缓存的情况下,设置了相同 cacheKey 的请求将会被缓存和复用。

  • 新增 runAsyncrefreshAsync,将返回 Promise

  • 新增 definePlugin,可以通过插件来扩展 useRequest 的功能。

  • 节流/防抖模式下可以使用 runAsync 返回正常的 Promise

  • 新增 useRequestProvider hooks,用于注入 options 配置。

  • 新增 refreshDepsAction 选项,用于自定义 refreshDeps 触发后的行为。

  • refreshDepsActionmanual=true 时,也会被 refreshDeps 的改变而触发。

  • 新增 loadingKeep

  • 移除 内部集成请求库,service 不再支持字符或对象。 迁移帮助

  • 移除 formatResult 迁移帮助

  • 移除 queryKey,即移除了并行模式 迁移帮助

  • run 不再返回 Promise 迁移帮助

  • 请求出错时,data 不再会被清空#82

  • 修改 ready 的逻辑 迁移帮助

  • ready 支持传入一个返回布尔值的函数 #166

  • dataerror 改为 shallowRef

  • usePagination 移除了 reload 方法和 reloading。如需要对应的需求,可自行实现。

  • 移除了 RequestConfig 组件 迁移帮助

  • 重构了useLoadMore,具体 API 可查看详情 API 说明

  • cacheKey 支持传入函数: cacheKey: (params?: P) => string

  • refreshDeps支持传入 一个函数,返回一个值 、是一个 ref 、一个响应式对象 或是由以上类型的值组成的数组 #166

    useRequest(getUser,{
      cacheKey: (params?:P):string => {
        <!-- 初始化时,params 会为 undefined,需要手动判断并返回一个空字符串 -->
        if(params){
          return `user-key-${params[0].name}`
        }
        return ''
      }
    })
  • 部分options 支持响应式,如下所示

    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>;
    };

迁移帮助

  1. service 不再支持字符或对象。期望用户可以根据其他第三方请求库进行封装(如 axios),只要提供 Promise 即可
const getUser = userName => {
  return axios.get("api/user", {
    params: {
      name: userName,
    },
  });
};
useRequest(getUser, options);
  1. 移除 formatResult。期望用户自行在 service 中返回最终格式的数据。
const getUser = async () => {
  const results = await axios.get("api/user");
  // 在此处处理最终的数据
  return results.data;
};
  1. 移除 queryKey,即移除了并行模式。期望将每个请求动作和 UI 封装为一个组件,而不是把所有请求都放到父级。

  2. 修改 ready 的逻辑

    • manual=false 时,每次 readyfalse 变为 true 时,都会自动发起请求,会带上参数 options.defaultParams
    • manual=true 时,只要 readyfalse,则无法发起请求。
  3. run 不再返回 Promise。直接用 runAsync 替代原本的 run

  4. 可自行通过 useRequestProvider 封装 。

useLoadMore API

Options

参数 说明 类型
manual 当设置为 true 时,你需要手动触发 loadMore 或者 loadMoreAsync 才会发起请求。默认为 false boolean
ready manual=false 时,每次 readyfalse 变为 true 时,都会自动触发 refresh。当 manual=true 时,只要 readyfalse,则无法发起请求。 Ref<boolean> | () => boolean
refreshDeps 改变后自动触发 refresh,如果设置了 refreshDepsAction 则触发 refreshDepsAction WatchSource<any> | WatchSource<any>[]
refreshDepsAction refreshDeps改变后触发 () => void
debounceInterval 以防抖策略处理请求 number | Ref<number>
debounceOptions 防抖参数 {leading: false, maxWait: undefined, trailing: true}
throttleInterval 以节流策略处理请求 number | Ref<number>
throttleOptions 节流参数 {leading: false, trailing: true}
errorRetryCount 发生错误时的错误重试次数 number | Ref<number>
errorRetryInterval 发生错误时的错误重试间隔时间 number | Ref<number>
isNoMore 判断是否还有更多数据 (data?: R) => boolean
onBefore service 执行前触发 () => void
onAfter service 执行完成时触发 () => void
onSuccess service resolve 时触发 (data: R) => void
onError service reject 时触发 (error: Error) => void

Result

参数 说明 类型
data service 返回的数据,必须包含 list 数组,类型为 { list: any[], ...other } Ref<R>
dataList datalist 数组 Ref<R['list']>
loading 是否正在进行请求 Ref<boolean>
loadingMore 是否正在加载更多 Ref<boolean>
noMore 是否有更多数据,需要配合 options.isNoMore 使用 Ref<boolean>
error service 返回的错误 Error
loadMore 加载更多数据,会自动捕获异常,通过 options.onError 处理 () => void
loadMoreAsync 加载更多数据,返回 Promise,需要自行处理错误 () => Promise<R>
refresh 刷新加载第一页数据,会自动捕获异常,通过 options.onError 处理 () => void
refreshAsync 刷新加载第一页数据,返回 Promise,需要自行处理错误 () => Promise<R>
mutate 直接修改 data 的结果 (arg: (oldData: R) => R) => void | (newData: R) => void
cancel 取消请求 () => void

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