// 引入 Vue 和 socket.io-client 库
import Vue from 'vue';
import io from 'socket.io-client';
// 创建一个 Vue 实例
new Vue({
el: '#app',
data: {
message: '',
messages: []
},
methods: {
// 发送消息的方法
sendMessage() {
if (this.message.trim() === '') return;
this.socket.emit('chat message', this.message);
this.message = '';
}
},
created() {
// 连接到 Socket.IO 服务器
this.socket = io('http://localhost:3000');
// 监听来自服务器的消息事件
this.socket.on('chat message', function(msg) {
this.messages.push(msg);
}.bind(this));
}
});
Vue 和 socket.io-client。socket.io-client 是用于客户端连接到 Socket.IO 服务器的库。message: 当前输入的消息内容。messages: 存储所有接收到的消息。io('http://localhost:3000') 连接到 Socket.IO 服务器。chat message 事件,并将接收到的消息添加到 messages 数组中。这样,你就可以通过 WebSocket 实现实时通信功能了。
上一篇:vue截取字符串方法
下一篇:vue 字符串转对象
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站