Vue.js WebSocket 整合指南:实时通信的完美解决方案
<template>
<div>
<input v-model="message" @keyup.enter="sendMessage" placeholder="输入消息">
<button @click="sendMessage">发送</button>
<ul>
<li v-for="message in messages" :key="message.id">
{{ message.content }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
message: '',
messages: [],
socket: null,
};
},
created() {
this.socket = new WebSocket('ws://your-websocket-server');
this.socket.onmessage = this.handleIncomingMessage;
},
methods: {
sendMessage() {
this.socket.send(JSON.stringify({ message: this.message }));
this.message = '';
},
handleIncomingMessage(event) {
const data = JSON.parse(event.data);
this.messages.push(data);
}
},
beforeDestroy() {
this.socket.close();
}
};
</script>
这个简单的Vue组件展示了如何在Vue.js应用中使用WebSocket进行实时通信。它包括创建WebSocket连接、发送消息和接收消息的基本逻辑。同时,它也展示了如何在组件销毁前关闭WebSocket连接,防止内存泄漏。
评论已关闭