基于Vue3封装一个好用的Websocket
在Vue 3中封装一个好用的WebSocket库,可以创建一个可复用的WebSocket连接管理类。以下是一个简单的示例:
// WebSocketManager.js
import { ref } from 'vue';
export default class WebSocketManager {
constructor(url) {
this.url = url;
this.socket = ref(null);
this.isConnected = ref(false);
this.connect();
}
connect() {
this.socket.value = new WebSocket(this.url);
this.socket.value.onopen = () => {
this.isConnected.value = true;
console.log('WebSocket connected');
};
this.socket.value.onerror = (error) => {
console.error('WebSocket error:', error);
};
this.socket.value.onmessage = (message) => {
console.log('Received message:', message.data);
// Handle incoming messages here
};
this.socket.value.onclose = () => {
this.isConnected.value = false;
console.log('WebSocket disconnected');
};
}
send(message) {
if (this.isConnected.value) {
this.socket.value.send(message);
} else {
console.error('WebSocket is not connected');
}
}
close() {
if (this.socket.value) {
this.socket.value.close();
}
}
}
使用该封装:
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import WebSocketManager from './WebSocketManager';
const app = createApp(App);
const webSocketManager = new WebSocketManager('wss://your-websocket-url');
app.config.globalProperties.$webSocketManager = webSocketManager;
app.mount('#app');
在组件中使用:
<script setup>
import { ref } from 'vue';
const message = ref('');
const $webSocketManager = app.config.globalProperties.$webSocketManager;
function sendMessage() {
$webSocketManager.send(message.value);
}
</script>
<template>
<input v-model="message" placeholder="Type your message">
<button @click="sendMessage">Send</button>
</template>
这个封装提供了一个简单的WebSocket管理类,它处理连接、消息发送和关闭。它也提供了一个例子,展示了如何在Vue应用中使用该封装。
评论已关闭