vue中websocket的使用---详解
<template>
<div>
<p>WebSocket状态: {{ wsStatus }}</p>
<button @click="connectWebSocket">连接WebSocket</button>
<button @click="sendMessage" :disabled="wsStatus !== 'OPEN'">发送消息</button>
</div>
</template>
<script>
export default {
data() {
return {
ws: null,
wsStatus: 'CLOSED',
};
},
methods: {
connectWebSocket() {
this.ws = new WebSocket('ws://your-websocket-server');
this.ws.onopen = () => {
this.wsStatus = 'OPEN';
console.log('WebSocket连接成功');
};
this.ws.onclose = () => {
this.wsStatus = 'CLOSED';
console.log('WebSocket连接已关闭');
};
this.ws.onerror = error => {
console.error('WebSocket出错:', error);
};
this.ws.onmessage = message => {
console.log('收到消息:', message.data);
};
},
sendMessage() {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
this.ws.send('你的消息内容');
}
}
},
beforeDestroy() {
if (this.ws) {
this.ws.close();
}
}
};
</script>
这个代码示例展示了如何在Vue组件中创建和管理WebSocket连接。它包括了连接WebSocket服务器、发送消息、处理打开、关闭和错误事件以及在组件销毁前关闭WebSocket连接的逻辑。
评论已关闭