vue3中封装使用WebSocket
时间: 2025-07-09 17:51:29 浏览: 13
<think>嗯,用户想在Vue3中封装和使用WebSocket,需要教程和示例。首先,我得回忆一下之前用户提供的引用内容。引用[1]提到了在Vue.js项目中封装WebSocket工具的基本示例,引用[2]有测试用例和工具文档地址,引用[3]是用户自己在Vue3中使用WebSocket的代码片段。这些信息应该结合起来。
首先,用户需要的是一个封装好的WebSocket工具类,这样可以在多个组件中复用。根据引用[1]和[3],可能需要创建一个类,处理连接、消息接收、错误处理和重连逻辑。在Vue3中,使用Composition API会更合适,比如用ref和reactive来管理状态。
然后,考虑如何将WebSocket实例化,并处理不同的生命周期事件,比如onopen、onmessage、onclose、onerror。引用[3]中的代码展示了如何创建WebSocket对象并设置这些事件监听器,但需要将其封装成可复用的模块。
另外,用户可能关心如何在不同组件中使用这个封装好的工具。可能需要使用provide/inject或者导出一个单例实例,方便全局使用。引用[2]提到的npm包可能是一个参考,但用户可能更倾向于自己封装而不是使用第三方库。
还要考虑TypeScript的支持,因为引用[2]和[3]都涉及到TypeScript。所以封装的类和方法需要类型声明,比如定义事件回调的类型,消息数据的类型等。
重连机制也是一个关键点,用户可能在连接断开时希望自动重新连接。需要设置重试次数和间隔,避免无限重试导致性能问题。
最后,提供一个使用示例,展示如何在Vue组件中导入这个封装类,发送消息,处理接收到的数据,并在组件卸载时关闭连接。同时,需要注意在onUnmounted生命周期钩子中清理事件监听器,防止内存泄漏。
可能还需要考虑WebSocket的状态管理,比如readyState,方便组件知道当前连接状态。引用[3]中有提到readyState的监听,可以将其暴露出来供组件使用。
总结步骤应该是:创建WebSocket工具类,处理连接和事件,实现重连机制,在Vue组件中使用,并提供示例代码。同时注意TypeScript类型和Vue3的生命周期整合。</think>### Vue3封装WebSocket的完整实现教程
#### 一、创建WebSocket工具类
新建`websocket.ts`文件,实现以下核心功能:
```typescript
import { ref, type Ref } from 'vue'
type MessageHandler = (data: any) => void
type StatusHandler = (status: number) => void
class WebSocketTool {
private socket: WebSocket | null = null
private retryCount = 0
private readonly maxRetries = 5
// 响应式状态管理
public status: Ref<number> = ref(0)
public messages: Ref<any> = ref(null)
constructor(
private readonly url: string,
private protocols?: string | string[]
) {}
connect() {
this.socket = new WebSocket(this.url, this.protocols)
this.status.value = this.socket.readyState
this.socket.onopen = () => {
this.status.value = 1
this.retryCount = 0
}
this.socket.onmessage = (event) => {
try {
this.messages.value = JSON.parse(event.data)
} catch {
this.messages.value = event.data
}
}
this.socket.onclose = (event) => {
this.status.value = 3
if (!event.wasClean && this.retryCount < this.maxRetries) {
setTimeout(() => {
this.retryCount++
this.connect()
}, 3000)
}
}
this.socket.onerror = () => {
this.status.value = 2
}
}
send(data: string | ArrayBuffer | Blob) {
if (this.socket?.readyState === 1) {
this.socket.send(data)
}
}
close(code?: number, reason?: string) {
this.socket?.close(code, reason)
}
}
export const createWebSocket = (url: string) => {
return new WebSocketTool(url)
}
```
#### 二、在组件中使用
```vue
<script setup lang="ts">
import { createWebSocket } from '@/utils/websocket'
import { onUnmounted, watch } from 'vue'
const ws = createWebSocket('wss://echo.websocket.org')
// 初始化连接
ws.connect()
// 监听消息变化
watch(ws.messages, (newVal) => {
console.log('收到消息:', newVal)
})
// 发送测试消息
const sendMessage = () => {
ws.send(JSON.stringify({ type: 'ping', time: Date.now() }))
}
// 组件卸载时关闭连接
onUnmounted(() => {
ws.close(1000, 'normal close')
})
</script>
<template>
<div>
<p>连接状态:{{ ws.status }}</p>
<button @click="sendMessage">发送测试消息</button>
<div v-if="ws.messages">
最新消息:{{ ws.messages }}
</div>
</div>
</template>
```
#### 三、核心功能说明
1. **状态管理**:
- 使用`ref`实现响应式状态跟踪
- 连接状态对应值:
- 0: CONNECTING
- 1: OPEN
- 2: CLOSING
- 3: CLOSED
2. **自动重连机制**:
- 非正常关闭时自动重试
- 最大重试次数5次,间隔3秒
- 重连计数器自动重置
3. **消息处理**:
- 自动尝试JSON解析
- 支持文本、二进制数据格式
- 通过`watch`实现响应式更新
[^1][^2]
#### 四、高级配置建议
1. **心跳检测**:
```typescript
private startHeartbeat() {
setInterval(() => {
if (this.status.value === 1) {
this.send(JSON.stringify({ type: 'heartbeat' }))
}
}, 30000)
}
```
2. **消息队列**:
```typescript
private messageQueue: any[] = []
send(data: any) {
if (this.status.value !== 1) {
this.messageQueue.push(data)
} else {
// 实际发送逻辑
}
}
```
3. **类型安全增强**:
```typescript
interface WebSocketMessage {
type: 'text' | 'binary'
content: string | ArrayBuffer
}
```
阅读全文
相关推荐

















