VUE3+WebSocket 连接教程
·
安装依赖
确保项目已初始化,若需安装 WebSocket 客户端库(如 websocket 或原生 API),可直接使用浏览器原生支持的 WebSocket 对象,无需额外安装。
创建 WebSocket 连接
在 Vue3 组件中,通过 setup 或 onMounted 生命周期钩子初始化 WebSocket 连接。需提供 WebSocket 服务器的 URL(如 ws://localhost:8080)。
import { onMounted, onBeforeUnmount, ref } from 'vue';
export default {
setup() {
const socket = ref(null);
const messages = ref([]);
onMounted(() => {
socket.value = new WebSocket('ws://localhost:8080');
socket.value.onopen = () => {
console.log('WebSocket 连接已建立');
};
socket.value.onmessage = (event) => {
messages.value.push(event.data);
};
socket.value.onerror = (error) => {
console.error('WebSocket 错误:', error);
};
socket.value.onclose = () => {
console.log('WebSocket 连接已关闭');
};
});
}
};
发送数据
通过 socket.value.send() 方法向服务器发送数据。可在方法中封装发送逻辑,例如响应按钮点击事件。
const sendMessage = () => {
if (socket.value && socket.value.readyState === WebSocket.OPEN) {
socket.value.send(JSON.stringify({ content: 'Hello WebSocket' }));
} else {
console.error('WebSocket 未连接');
}
};
关闭连接
在组件卸载时(onBeforeUnmount 钩子)关闭 WebSocket 连接,避免资源泄漏。
onBeforeUnmount(() => {
if (socket.value) {
socket.value.close();
}
});
处理重连机制
为提升稳定性,可添加自动重连逻辑。通过定时器在连接断开后尝试重新连接
const reconnectAttempts = ref(0);
const maxReconnectAttempts = 5;
socket.value.onclose = () => {
if (reconnectAttempts.value < maxReconnectAttempts) {
setTimeout(() => {
socket.value = new WebSocket('ws://localhost:8080');
reconnectAttempts.value++;
}, 3000);
}
};
完整示例代码
以下是一个整合了上述功能的 Vue3 组件示例:
<template>
<div>
<button @click="sendMessage">发送消息</button>
<ul>
<li v-for="(msg, index) in messages" :key="index">{{ msg }}</li>
</ul>
</div>
</template>
<script>
import { onMounted, onBeforeUnmount, ref } from 'vue';
export default {
setup() {
const socket = ref(null);
const messages = ref([]);
const reconnectAttempts = ref(0);
const maxReconnectAttempts = 5;
const initWebSocket = () => {
socket.value = new WebSocket('ws://localhost:8080');
socket.value.onopen = () => {
console.log('WebSocket 连接已建立');
reconnectAttempts.value = 0;
};
socket.value.onmessage = (event) => {
messages.value.push(event.data);
};
socket.value.onerror = (error) => {
console.error('WebSocket 错误:', error);
};
socket.value.onclose = () => {
if (reconnectAttempts.value < maxReconnectAttempts) {
setTimeout(initWebSocket, 3000);
reconnectAttempts.value++;
}
};
};
const sendMessage = () => {
if (socket.value?.readyState === WebSocket.OPEN) {
socket.value.send(JSON.stringify({ content: 'Hello WebSocket' }));
}
};
onMounted(initWebSocket);
onBeforeUnmount(() => {
if (socket.value) socket.value.close();
});
return { messages, sendMessage };
},
};
</script>
注意事项
- 跨域问题:确保 WebSocket 服务器允许前端域名的连接(通过 CORS 配置)。
- 协议一致性:开发环境与生产环境的 WebSocket 协议(
ws或wss)需匹配。 - 心跳检测:长时间连接建议添加心跳包机制,防止连接超时断开。
更多推荐
所有评论(0)