Skip to content

useWebSocket

反应式 WebSocket 客户端。

¥Reactive WebSocket client.

用法

¥Usage

ts
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.

如果 url 作为 ref 提供,则当 url 发生更改时,它会自动重新连接到新的 url。

¥If url is provided as a ref, when the url changes, it will automatically reconnect to the new url.

autoClose

默认启用。

¥Enable by default.

当触发 beforeunload 事件或相关效果范围停止时,这将自动调用 close()

¥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).

ts
const { 
status
,
data
,
close
} =
useWebSocket
('ws://websocketurl', {
autoReconnect
: true,
})

或者对其行为进行更多控制:

¥Or with more controls over its behavior:

ts
const { 
status
,
data
,
close
} =
useWebSocket
('ws://websocketurl', {
autoReconnect
: {
retries
: 3,
delay
: 1000,
onFailed
() {
alert
('Failed to connect WebSocket after 3 retries')
}, }, })

显式调用 close() 不会触发自动重新连接。

¥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:

ts
const { 
status
,
data
,
close
} =
useWebSocket
('ws://websocketurl', {
heartbeat
: true,
})

或者使用更多控件:

¥Or with more controls:

ts
const { 
status
,
data
,
close
} =
useWebSocket
('ws://websocketurl', {
heartbeat
: {
message
: 'ping',
interval
: 1000,
pongTimeout
: 1000,
}, })

子协议

¥Sub-protocols

要使用的一个或多个子协议的列表,在本例中为肥皂和 wamp。

¥List of one or more subprotocols to use, in this case soap and wamp.

ts
const { 
status
,
data
,
send
,
open
,
close
} =
useWebSocket
('ws://websocketurl', {
protocols
: ['soap'], // ['soap', 'wamp']
})