下载websocket插件
npm install websocket
基础步骤
<template>
<div class="hello">
<input type="text" v-model="sendContent">
<button @click="sendMessage">发送</button>
<div>
<div v-for="(item, index) in messages" :key="index">
<div>名字:{{ item.username }}</div>
<div>消息:{{ item.content }}</div>
<hr>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
socket: null,
messages: [],
sendContent: ""
}
},
created() {
// 创建 WebSocket 连接
this.socket = new WebSocket('ws://8.222.189.229:3000');
// 监听 WebSocket 连接事件
this.socket.addEventListener('open', event => {
console.log('WebSocket 连接已建立', event);
});
// 监听 WebSocket 接收消息事件
this.socket.addEventListener('message', event => {
const message = JSON.parse(event.data);
this.messages.push(JSON.parse(message))
console.log(this.messages)
});
},
methods: {
sendMessage() {
const message = {
username: '小白',
content: this.sendContent
};
this.socket.send(JSON.stringify(message));
this.messages.push({ ...message })
this.sendContent = ""
}
}
}
</script>