Collection of essential Vue Composition Utilities providing 146+ reactive composable functions for Vue 3 applications
—
HTTP client utilities, WebSocket management, and browser communication APIs for data fetching, real-time communication, and inter-tab messaging.
Comprehensive reactive fetch wrapper with extensive configuration options.
/**
* Reactive fetch wrapper with extensive options
* @param url - Request URL (reactive)
* @param options - Standard fetch options
* @param useFetchOptions - VueUse specific options
* @returns Fetch utilities and state
*/
function useFetch<T>(
url: MaybeRefOrGetter<string>,
options?: RequestInit,
useFetchOptions?: UseFetchOptions
): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
interface UseFetchReturn<T> {
// State
isFinished: Ref<boolean>;
isFetching: Ref<boolean>;
aborted: Ref<boolean>;
statusCode: Ref<number | null>;
response: Ref<Response | null>;
error: Ref<any>;
data: Ref<T | null>;
// Methods
abort: () => void;
execute: (throwOnFailed?: boolean) => Promise<UseFetchReturn<T>>;
get: () => UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
post: (payload?: MaybeRefOrGetter<unknown>, type?: string) => UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
put: (payload?: MaybeRefOrGetter<unknown>, type?: string) => UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
delete: () => UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
patch: (payload?: MaybeRefOrGetter<unknown>, type?: string) => UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
head: () => UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
options: () => UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
// Type helpers
json: <JSON = any>() => UseFetchReturn<JSON> & PromiseLike<UseFetchReturn<JSON>>;
text: () => UseFetchReturn<string> & PromiseLike<UseFetchReturn<string>>;
blob: () => UseFetchReturn<Blob> & PromiseLike<UseFetchReturn<Blob>>;
arrayBuffer: () => UseFetchReturn<ArrayBuffer> & PromiseLike<UseFetchReturn<ArrayBuffer>>;
formData: () => UseFetchReturn<FormData> & PromiseLike<UseFetchReturn<FormData>>;
}
interface UseFetchOptions {
immediate?: boolean;
refetch?: MaybeRefOrGetter<boolean>;
initialData?: any;
timeout?: number;
beforeFetch?: (ctx: BeforeFetchContext) => Promise<Partial<BeforeFetchContext> | void> | Partial<BeforeFetchContext> | void;
afterFetch?: (ctx: AfterFetchContext) => Promise<Partial<AfterFetchContext>> | Partial<AfterFetchContext>;
onFetchError?: (ctx: OnFetchErrorContext) => Promise<Partial<OnFetchErrorContext>> | Partial<OnFetchErrorContext>;
updateDataOnError?: boolean;
}Usage Examples:
import { useFetch } from "@vueuse/core";
// Basic GET request
const { data, isFetching, error } = useFetch('/api/users').json();
// POST request with payload
const { data, execute } = useFetch('/api/users', {
immediate: false
}).post({ name: 'John', email: 'john@example.com' });
await execute();
// Reactive URL
const userId = ref('123');
const { data } = useFetch(computed(() => `/api/users/${userId.value}`)).json();
// With interceptors
const { data } = useFetch('/api/protected', {
beforeFetch({ url, options }) {
options.headers = {
...options.headers,
Authorization: `Bearer ${token.value}`,
};
return { options };
},
afterFetch(ctx) {
ctx.data = transformData(ctx.data);
return ctx;
}
}).json();
// Error handling
const { data, error, statusCode } = useFetch('/api/data', {
onFetchError({ error, response }) {
console.error('Fetch failed:', error);
if (response?.status === 401) {
// Handle unauthorized
redirectToLogin();
}
}
}).json();Create a custom fetch composable with base configuration.
/**
* Create a custom fetch composable with base configuration
* @param config - Base configuration for all requests
* @returns Configured fetch function
*/
function createFetch(config?: CreateFetchOptions): typeof useFetch;
interface CreateFetchOptions {
baseUrl?: MaybeRefOrGetter<string>;
combination?: 'overwrite' | 'chain';
options?: RequestInit;
fetchOptions?: Omit<UseFetchOptions, 'immediate'>;
}Usage Examples:
import { createFetch } from "@vueuse/core";
// Create API client
const useAPI = createFetch({
baseUrl: 'https://api.example.com',
options: {
headers: {
'Content-Type': 'application/json',
},
},
fetchOptions: {
beforeFetch({ options }) {
options.headers = {
...options.headers,
Authorization: `Bearer ${getToken()}`,
};
return { options };
},
},
});
// Use the configured client
const { data } = useAPI('/users').json();
const { data: user } = useAPI('/users/123').json();Reactive WebSocket client with auto-reconnection and buffer management.
/**
* Reactive WebSocket client with auto-reconnection
* @param url - WebSocket URL (reactive)
* @param options - Configuration options
* @returns WebSocket state and utilities
*/
function useWebSocket<Data = any>(
url: MaybeRefOrGetter<string | URL | undefined>,
options?: UseWebSocketOptions
): UseWebSocketReturn<Data>;
interface UseWebSocketReturn<Data> {
data: Ref<Data | null>;
status: Ref<UseWebSocketStatus>;
close: WebSocket['close'];
open: () => void;
send: (data: string | ArrayBuffer | Blob, useBuffer?: boolean) => void;
ws: Ref<WebSocket | undefined>;
}
interface UseWebSocketOptions {
onConnected?: (ws: WebSocket) => void;
onDisconnected?: (ws: WebSocket, event: CloseEvent) => void;
onError?: (ws: WebSocket, event: Event) => void;
onMessage?: (ws: WebSocket, event: MessageEvent) => void;
immediate?: boolean;
autoClose?: boolean;
autoReconnect?: boolean | UseWebSocketAutoReconnectOptions;
protocols?: string[];
heartbeat?: boolean | UseWebSocketHeartbeatOptions;
}
interface UseWebSocketAutoReconnectOptions {
retries?: number;
delay?: number;
onFailed?: () => void;
}
interface UseWebSocketHeartbeatOptions {
message?: string | (() => string);
interval?: number;
pongTimeout?: number;
}
type UseWebSocketStatus = 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED';Usage Examples:
import { useWebSocket } from "@vueuse/core";
// Basic WebSocket connection
const { status, data, send, open, close } = useWebSocket('ws://localhost:8080');
// Send message
send('Hello Server!');
// With JSON serialization
const { data, send } = useWebSocket('ws://localhost:8080', {
onMessage: (ws, event) => {
console.log('Received:', JSON.parse(event.data));
}
});
send(JSON.stringify({ type: 'message', content: 'Hello' }));
// Auto-reconnection
const { status } = useWebSocket('ws://localhost:8080', {
autoReconnect: {
retries: 3,
delay: 1000,
onFailed() {
console.log('Failed to reconnect WebSocket after 3 attempts');
}
}
});
// Heartbeat
const { status } = useWebSocket('ws://localhost:8080', {
heartbeat: {
message: 'ping',
interval: 30000, // 30 seconds
pongTimeout: 5000 // 5 seconds
}
});Reactive BroadcastChannel API for inter-tab communication.
/**
* Reactive BroadcastChannel API for inter-tab communication
* @param name - Channel name
* @param options - Configuration options
* @returns BroadcastChannel utilities
*/
function useBroadcastChannel<D, P>(
name: string,
options?: UseBroadcastChannelOptions<D, P>
): UseBroadcastChannelReturn<D, P>;
interface UseBroadcastChannelReturn<D, P> {
isSupported: Ref<boolean>;
channel: Ref<BroadcastChannel | undefined>;
data: Ref<D>;
post: (data: P) => void;
close: () => void;
error: Ref<Event | null>;
isClosed: Ref<boolean>;
}
interface UseBroadcastChannelOptions<D, P> {
immediate?: boolean;
}Reactive URLSearchParams management.
/**
* Reactive URLSearchParams management
* @param mode - Update mode for URL changes
* @param options - Configuration options
* @returns Reactive search params utilities
*/
function useUrlSearchParams<T extends Record<string, any> = Record<string, string>>(
mode?: 'history' | 'hash' | 'hash-params',
options?: UseUrlSearchParamsOptions
): T;
interface UseUrlSearchParamsOptions {
removeNullishValues?: boolean;
removeFalsyValues?: boolean;
write?: boolean;
window?: Window;
}Usage Examples:
import { useUrlSearchParams } from "@vueuse/core";
// Basic usage
const params = useUrlSearchParams('history');
// Get/set search params
console.log(params.q); // Get 'q' parameter
params.q = 'vue'; // Set 'q' parameter
// Reactive to URL changes
watchEffect(() => {
if (params.page) {
loadPage(params.page);
}
});
// Typed parameters
const params = useUrlSearchParams<{
page?: string;
limit?: string;
q?: string;
}>('history');Reactive EventSource (Server-Sent Events) client.
/**
* Reactive EventSource (Server-Sent Events) client
* @param url - EventSource URL (reactive)
* @param events - Event names to listen for
* @param options - Configuration options
* @returns EventSource state and utilities
*/
function useEventSource(
url: MaybeRef<string | URL>,
events?: Array<string>,
options?: UseEventSourceOptions
): UseEventSourceReturn;
interface UseEventSourceReturn {
eventSource: Ref<EventSource | null>;
event: Ref<string | null>;
data: Ref<string | null>;
status: Ref<UseEventSourceStatus>;
error: Ref<Event | null>;
close: () => void;
}
interface UseEventSourceOptions extends ConfigurableWindow {
immediate?: boolean;
autoReconnect?: boolean | UseEventSourceAutoReconnectOptions;
withCredentials?: boolean;
}
type UseEventSourceStatus = 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED';Reactive Web Worker management.
/**
* Reactive Web Worker management
* @param url - Worker script URL
* @param options - Configuration options
* @returns Web Worker utilities
*/
function useWebWorker<T = any>(
url: MaybeRefOrGetter<string>,
options?: UseWebWorkerOptions
): UseWebWorkerReturn<T>;
interface UseWebWorkerReturn<T> {
data: Ref<T>;
worker: Ref<Worker | undefined>;
post: typeof Worker.prototype.postMessage;
terminate: () => void;
}Run function in Web Worker with automatic serialization.
/**
* Run function in Web Worker with automatic serialization
* @param fn - Function to run in worker
* @param options - Configuration options
* @returns Worker function utilities
*/
function useWebWorkerFn<T extends (...fnArgs: any[]) => any>(
fn: T,
options?: UseWebWorkerFnOptions
): UseWebWorkerFnReturn<T>;
interface UseWebWorkerFnReturn<T> {
workerFn: (...fnArgs: Parameters<T>) => Promise<ReturnType<T>>;
workerStatus: Ref<UseWebWorkerStatus>;
workerTerminate: (timeout?: number) => void;
}
type UseWebWorkerStatus = 'PENDING' | 'SUCCESS' | 'RUNNING' | 'ERROR' | 'TIMEOUT_EXPIRED';Install with Tessl CLI
npx tessl i tessl/npm-vueuse--core