vue websocket demo
时间: 2023-06-23 22:50:03 浏览: 67
以下是一个简单的 Vue.js WebSocket 示例:
首先,在 Vue.js 中使用 WebSocket,我们需要使用 `WebSocket` 对象。在 Vue.js 中,我们可以在 `created()` 钩子函数中创建 WebSocket 连接,并在 `beforeDestroy()` 钩子函数中关闭连接以避免内存泄漏。
接下来,我们可以在 `methods` 对象中定义发送和接收消息的方法。发送消息只需要将消息发送到 WebSocket 连接即可,而接收消息则需要监听 `message` 事件并将接收到的消息存储在数据中以供渲染。
最后,我们可以在模板中渲染消息列表并使用 `v-model` 指令绑定一个输入框来发送消息。
下面是一个简单的 Vue.js WebSocket 示例代码:
```html
<template>
<div>
<ul>
<li v-for="message in messages" :key="message.id">
{{ message.text }}
</li>
</ul>
<input type="text" v-model="newMessage" @keydown.enter="sendMessage">
</div>
</template>
<script>
export default {
data() {
return {
ws: null,
messages: [],
newMessage: ""
};
},
created() {
this.ws = new WebSocket("ws://localhost:3000");
this.ws.addEventListener("message", this.onMessage);
},
beforeDestroy() {
this.ws.close();
},
methods: {
onMessage(event) {
const message = JSON.parse(event.data);
this.messages.push(message);
},
sendMessage() {
const message = {
id: Date.now(),
text: this.newMessage
};
this.ws.send(JSON.stringify(message));
this.newMessage = "";
}
}
};
</script>
```
在这个示例中,我们创建了一个 WebSocket 对象并监听 `message` 事件。我们还定义了两个方法:`onMessage()` 和 `sendMessage()`。`onMessage()` 方法用于接收并解析 WebSocket 服务器发送的消息,并将其存储在 `messages` 数组中以供渲染。`sendMessage()` 方法用于将用户输入的消息发送到 WebSocket 服务器。
最后,在模板中,我们使用 `v-for` 指令渲染 `messages` 数组中的消息,并使用 `v-model` 指令绑定 `newMessage` 变量以便用户输入新消息。我们还在输入框上绑定 `@keydown.enter` 事件监听器,以便在用户按下 Enter 键时发送消息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)