Skip to content

Latest commit

 

History

History
82 lines (58 loc) · 1.7 KB

index.md

File metadata and controls

82 lines (58 loc) · 1.7 KB
category
Misc

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

Auto-connect (enabled by default).

This will call open() automatically for you and you don't need to call it by yourself.

Auto-reconnection

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 retires')
    },
  },
})

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,
  },
})

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']
})