useWebSocket

Reactive simple WebSocket client.

Usage

import { useWebSocket } from '@vueuse/core'

const { state, data, send, close, ws } = useWebSocket('ws://websocketurl')
StateTypeDescription
stateRef<string>The current websocket state, can be only one of: 'OPEN', 'CONNECTING', 'CLOSING', 'CLOSED'
dataRef<object>Reference to the latest data received via the websocket, can be watched to respond to incoming messages
MethodSignatureDescription
send(data: any) => voidSends data through the websocket connection.
close(code?: number, reason?: string) => voidCloses the websocket connection gracefully.
InstanceTypeDescription
wsWebSocket<object>WebSocket instance.

Type Declarations

export declare type WebSocketStatus =
  | "OPEN"
  | "CONNECTING"
  | "CLOSING"
  | "CLOSED"
/**
 * Reactive simple WebSocket client.
 *
 * @see   {@link /useWebSocket}
 * @param url
 */
export declare function useWebSocket(
  url: string
): {
  data: Ref<any>
  state: Ref<WebSocketStatus>
  close: (code?: number | undefined, reason?: string | undefined) => void
  send: (
    data: string | Blob | ArrayBuffer | SharedArrayBuffer | ArrayBufferView
  ) => void
  ws: WebSocket
}

Source

SourceDocs