useWebSocket
管理 websocket
Demo
webScoket状态: -1
Usage
html
<template>
<div>
<div>webScoket状态: {{ readyState }}</div>
<button @click="connect">连接webScoket</button>
<button @click="disconnect">关闭webScoket</button>
<button @click="handleSendMessage">发送消息</button>
</div>
</template>
<script lang="ts" setup>
import { watchEffect } from 'vue'
import { useWebSocket } from '@morehook/core'
const { connect, readyState, latestMessage, disconnect, sendMessage } =
useWebSocket('ws://127.0.0.1:8080')
const handleSendMessage = () => {
sendMessage('hello v3hooks')
}
watchEffect(() => {
console.log(latestMessage.value)
})
</script>
Type Declarations
Show Type Declarations
typescript
/**
* manual: 是否手动连接 (默认false)
* reconnectLimit: 重连数
* reconnectInterval: 重连间隔时间
* onOpen: 打开连接回调
* onClose: 关闭连接回调
* onMessage: 发送消息回调
* onError: 连接报错回调
*/
interface UseWebSocketOptions {
manual?: boolean
reconnectLimit?: number
reconnectInterval?: number
onOpen?: (event: WebSocketEventMap["open"]) => void
onClose?: (event: WebSocketEventMap["close"]) => void
onMessage?: (event: WebSocketEventMap["message"]) => void
onError?: (event: WebSocketEventMap["error"]) => void
}
declare enum ReadyState {
Connecting = 0,
Open = 1,
Closing = 2,
Closed = 3,
}
/**
* connect: 连接方法
* disconnect: 关闭连接方法
* sendMessage: 发送消息方法
* readyState: 当前连接状态
* latestMessage: 最后返回的消息
* webSocketIns: 连接实例
*/
interface Result {
connect: () => void
disconnect: () => void
sendMessage: WebSocket["send"]
readyState: Ref<ReadyState>
latestMessage: Ref<WebSocketEventMap["message"] | undefined>
webSocketIns: Ref<WebSocket | undefined>
}
/**
* 管理 websocket
* @param socketUrl 连接地址
* @param options UseWebSocketOptions
* @return Result
*/
export declare function useWebSocket(
socketUrl: string,
options?: UseWebSocketOptions
): Result