vue中websocket的完整使用
时间: 2023-11-24 19:04:26 浏览: 75
Vue中使用WebSocket需要以下步骤:
1. 在Vue组件中引入WebSocket库:
```
import WebSocket from "websocket";
```
2. 创建WebSocket实例,连接服务器:
```
let ws = new WebSocket("ws://localhost:8000");
ws.onopen = function() {
console.log("Connected to WebSocket server!");
};
```
3. 监听WebSocket事件,处理接收到的消息:
```
ws.onmessage = function(event) {
console.log("Received message:", event.data);
};
```
4. 发送消息给服务器:
```
ws.send("Hello server!");
```
完整代码示例:
```
<template>
<div>
<h1>WebSocket Demo</h1>
<div v-for="message in messages" :key="message">{{ message }}</div>
</div>
</template>
<script>
import WebSocket from "websocket";
export default {
name: "WebSocketDemo",
data() {
return {
ws: null,
messages: []
};
},
mounted() {
this.connectWebSocket();
},
methods: {
connectWebSocket() {
this.ws = new WebSocket("ws://localhost:8000");
this.ws.onopen = () => {
console.log("Connected to WebSocket server!");
};
this.ws.onmessage = event => {
console.log("Received message:", event.data);
this.messages.push(event.data);
};
this.ws.onclose = () => {
console.log("Disconnected from WebSocket server!");
};
},
sendMessage() {
let message = prompt("Enter message to send:");
this.ws.send(message);
}
}
};
</script>
```
阅读全文