useWebSocket
Reactive WebSocket client.
Usage
import { useWebSocket } from '@vueuse/core'
const { status, data, send, open, close } = useWebSocket('ws://websocketurl')
See the Type Declarations for more options.
immediate
Enable by default.
Establish the connection immediately when the composable is called.
autoConnect
Enable by default.
If url is provided as a ref, when the url changes, it will automatically reconnect to the new url.
autoClose
Enable by default.
This will call close()
automatically when the beforeunload
event is triggered or the associated effect scope is stopped.
autoReconnect
Reconnect on errors automatically (disabled by default).
const { status, data, close } = useWebSocket('ws://websocketurl', {
autoReconnect: true,
})
Or with more controls over its behavior:
const { status, data, close } = useWebSocket('ws://websocketurl', {
autoReconnect: {
retries: 3,
delay: 1000,
onFailed() {
alert('Failed to connect WebSocket after 3 retries')
},
},
})
Explicitly calling close()
won't trigger the auto reconnection.
heartbeat
It's common practice to send a small message (heartbeat) for every given time passed to keep the connection active. In this function we provide a convenient helper to do it:
const { status, data, close } = useWebSocket('ws://websocketurl', {
heartbeat: true,
})
Or with more controls:
const { status, data, close } = useWebSocket('ws://websocketurl', {
heartbeat: {
message: 'ping',
interval: 1000,
pongTimeout: 1000,
},
})
Sub-protocols
List of one or more subprotocols to use, in this case soap and wamp.
import { useWebSocket } from '@vueuse/core'
const { status, data, send, open, close } = useWebSocket('ws://websocketurl', {
protocols: ['soap'], // ['soap', 'wamp']
})
Type Declarations
Show Type Declarations
export type WebSocketStatus = "OPEN" | "CONNECTING" | "CLOSED"
export type WebSocketHeartbeatMessage = string | ArrayBuffer | Blob
export interface UseWebSocketOptions {
onConnected?: (ws: WebSocket) => void
onDisconnected?: (ws: WebSocket, event: CloseEvent) => void
onError?: (ws: WebSocket, event: Event) => void
onMessage?: (ws: WebSocket, event: MessageEvent) => void
/**
* Send heartbeat for every x milliseconds passed
*
* @default false
*/
heartbeat?:
| boolean
| {
/**
* Message for the heartbeat
*
* @default 'ping'
*/
message?: MaybeRefOrGetter<WebSocketHeartbeatMessage>
/**
* Response message for the heartbeat, if undefined the message will be used
*/
responseMessage?: MaybeRefOrGetter<WebSocketHeartbeatMessage>
/**
* Interval, in milliseconds
*
* @default 1000
*/
interval?: number
/**
* Heartbeat response timeout, in milliseconds
*
* @default 1000
*/
pongTimeout?: number
}
/**
* Enabled auto reconnect
*
* @default false
*/
autoReconnect?:
| boolean
| {
/**
* Maximum retry times.
*
* Or you can pass a predicate function (which returns true if you want to retry).
*
* @default -1
*/
retries?: number | ((retried: number) => boolean)
/**
* Delay for reconnect, in milliseconds
*
* @default 1000
*/
delay?: number
/**
* On maximum retry times reached.
*/
onFailed?: Fn
}
/**
* Immediately open the connection when calling this composable
*
* @default true
*/
immediate?: boolean
/**
* Automatically connect to the websocket when URL changes
*
* @default true
*/
autoConnect?: boolean
/**
* Automatically close a connection
*
* @default true
*/
autoClose?: boolean
/**
* List of one or more sub-protocol strings
*
* @default []
*/
protocols?: string[]
}
export interface UseWebSocketReturn<T> {
/**
* Reference to the latest data received via the websocket,
* can be watched to respond to incoming messages
*/
data: Ref<T | null>
/**
* The current websocket status, can be only one of:
* 'OPEN', 'CONNECTING', 'CLOSED'
*/
status: ShallowRef<WebSocketStatus>
/**
* Closes the websocket connection gracefully.
*/
close: WebSocket["close"]
/**
* Reopen the websocket connection.
* If there the current one is active, will close it before opening a new one.
*/
open: Fn
/**
* Sends data through the websocket connection.
*
* @param data
* @param useBuffer when the socket is not yet open, store the data into the buffer and sent them one connected. Default to true.
*/
send: (data: string | ArrayBuffer | Blob, useBuffer?: boolean) => boolean
/**
* Reference to the WebSocket instance.
*/
ws: Ref<WebSocket | undefined>
}
/**
* Reactive WebSocket client.
*
* @see https://vueuse.org/useWebSocket
* @param url
*/
export declare function useWebSocket<Data = any>(
url: MaybeRefOrGetter<string | URL | undefined>,
options?: UseWebSocketOptions,
): UseWebSocketReturn<Data>
Source
Contributors
Changelog
v12.8.0
on v12.4.0
on v12.3.0
on 59f75
- feat(toValue): deprecate toValue
from @vueuse/shared
in favor of Vue's nativev12.1.0
on v11.2.0
on v11.0.2
on v10.10.0
on v10.8.0
on v10.6.0
on v10.5.0
on v10.4.0
on 4d757
- feat(types)!: rename MaybeComputedRef
to MaybeRefOrGetter
10e98
- feat(toRef)!: rename resolveRef
to toRef