useWebSocket

用于处理 WebSocket 的 Hook。

基础使用

<template>
  <div class="hello">
    <div>webScoket状态: {{readyState}}</div>
    <button @click="connect">连接webScoket</button>
    <button @click="disconnect">关闭webScoket</button>
    <button @click="handleSendMessage">发送消息</button>
  </div>
</template>

<script lang="ts">
import { useWebSocket } from "v3hooks";
import { watchEffect } from 'vue';
export default {

  setup() {

    const { 
      readyState,
      latestMessage,
      disconnect,
      sendMessage,
    } = useWebSocket('ws://82.157.123.54:9010/ajaxchattest')

    const handleSendMessage = ()=>{
      sendMessage('hello v3hooks')
    }

    watchEffect(()=>{
      console.log(latestMessage.value)
    })

    return {
      readyState,
      disconnect,
      handleSendMessage
    };
  },
};
</script>

useWebSocket接受一个string的socket地址,返回一个集合对象。 上面例子中接受参数使用了latestMessage来获取最新一次通讯的event对象。

也可以使用onMessage来获取event对象,如下

useWebSocket('ws://82.157.123.54:9010/ajaxchattest',{
  onMessage(event){
    console.log(event)
  }
})

Api

enum ReadyState {
    Connecting = 0,
    Open = 1,
    Closing = 2,
    Closed = 3
}
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;
}
interface Result {
    latestMessage: Ref<WebSocketEventMap['message'] | undefined>;
    sendMessage: WebSocket['send'];
    disconnect: () => void;
    connect: () => void;
    readyState: Ref<ReadyState>;
    webSocketIns: Ref<WebSocket | undefined>;
}
function useWebSocket(socketUrl: string, options?: UseWebSocketOptions): Result;

Params

Options

Result

最后更新于