跳转到内容

createRequest

createRequest is a factory function for creating request instances with bound data extraction logic.

Basic Usage

ts
import { createRequest } from 'vue-rex'

const useApi = createRequest({ dataKey: 'data' })

const { data, loading, error, run } = useApi(getUserList)

Configuration

dataKey

Data field path, supports dot notation. TypeScript automatically infers data.value type.

ts
// Extract res.data
const useApi = createRequest({ dataKey: 'data' })

// Extract res.result.data
const useApi = createRequest({ dataKey: 'result.data' })

options

Global defaults, overridden by local options when calling.

ts
const useApi = createRequest({
  dataKey: 'data',
  options: {
    refreshOnWindowFocus: true,
    debounceWait: 300,
  },
})

plugins

Global default plugins.

ts
import { createRequest, definePlugin } from 'vue-rex'

const logPlugin = definePlugin((ctx) => ({
  onBefore(params) {
    console.log('request start', params)
  },
}))

const useApi = createRequest({
  dataKey: 'data',
  plugins: [logPlugin],
})

Options

Full configuration for useApi(service, options):

Behavior

OptionTypeDefaultDescription
manualbooleanfalseManual trigger only, no auto-execute
readyRef<boolean>trueWhether request is allowed
defaultParamsTParams-Default params passed to service
watchSourcetrue | WatchSource | WatchSource[]-Watch sources, true for auto-collect
watchDeepbooleanfalseDeep watch

Loading

OptionTypeDefaultDescription
loadingDelayMaybeRef<number>-Delay before showing loading (ms)
loadingKeepMaybeRef<number>-Minimum loading duration (ms)

Debounce / Throttle

OptionTypeDefaultDescription
debounceWaitMaybeRef<number>500Debounce wait time (ms)
debounceMaxWaitMaybeRef<number>-Max debounce delay (ms)
debounceLeadingMaybeRef<boolean>falseInvoke on leading edge
debounceTrailingMaybeRef<boolean>trueInvoke on trailing edge
throttleWaitMaybeRef<number>500Throttle wait time (ms)
throttleLeadingMaybeRef<boolean>trueInvoke on leading edge
throttleTrailingMaybeRef<boolean>trueInvoke on trailing edge

Cache

OptionTypeDefaultDescription
cacheKeystring-Cache key, enables caching and global sharing
cacheTimenumber600000Cache expiration (ms), Infinity = never
staleTimenumber-Data freshness time (ms), no request during this window
getCache(key, params) => CachedData-Custom get cache
setCache(key, data) => void-Custom set cache

Error handling

OptionTypeDefaultDescription
errorRetryCountMaybeRef<number>-Error retry count, Infinity = unlimited
errorRetryIntervalMaybeRef<number>-Retry interval (ms)
throwOnErrorbooleanfalseThrow on error for try/catch usage

Polling

OptionTypeDefaultDescription
pollingIntervalMaybeRef<number>0Polling interval (ms), > 0 enables
pollingWhenDocumentHiddenMaybeRef<boolean>falseContinue polling when page hidden
pollingErrorRetryCountMaybeRef<number>3Polling error retry count

Window focus

OptionTypeDefaultDescription
refreshOnWindowFocusMaybeRef<boolean>falseRefresh on window focus
focusTimespanMaybeRef<number>5000Focus refresh throttle (ms)

Data

OptionTypeDefaultDescription
initialDataTFormatData-Initial value for data
formatData(data, rawData, params) => TFormatData-Post-process extracted data

Callbacks

OptionTypeDefaultDescription
onBefore(params) => void-Before request
onSuccess(data, rawData, params) => void-On success
onError(error, params) => void-On error
onFinally(params) => void-After request (success or error)
onFinallyFetchDone(params) => void-After last request in a sequence

Return Value

PropertyTypeDescription
dataComputedRef<TFormatData>Extracted and formatted data
rawDataComputedRef<TData>Raw service response
errorComputedRef<any>Error from rejected service
loadingComputedRef<boolean>Request in progress
finishedComputedRef<boolean>Request completed
paramsComputedRef<TParams>Current request params
run(...args) => PromiseManual trigger
debounceRun(...args) => PromiseDebounced run
throttleRun(...args) => PromiseThrottled run
refresh() => PromiseRe-run with last params
cancel() => voidCancel current request
mutate(data | fn) => voidDirectly modify data
optimisticUpdate(data | fn, params?) => voidOptimistic update, auto-rollback on failure