1、vue安装vue-socket.io:
npm i vue-socket.io
2、引入vue-socket.io
在main.js中
import VueSocketIO from "vue-socket.io"
Vue.use(new VueSocketIO({
debug: true,
connection: 'http://localhost:3000',
// vuex: {}
}))
3、在vue示例页面中使用
sockets: {
connect: function() {
console.log("socket connected");
this.id = this.$socket.id;
console.log('打印服务器分配的id:')
console.log(this.id)
},
customEmit: function(data) {
console.log(
'this method was fired by the socket server. eg: io.emit("customEmit", data)'
);
console.log(data);
}
},
customEmit是前后台约定的消息,自定义的。后台定义了消息的名字,前台就可以使用这个名字来接受相应的消息了。
比如这里是服务器代码:
发送消息很简单。在相应的事件中直接使用相应的代码就可以了:
this.$socket.emit("message", this.searchTitle);
message是约定的消息名字。可以自定义。
除了在sockets对象中监听,还可以在外部单独注册事件监听或者取消注册:
this.sockets.subscribe('EVENT_NAME', (data) => {
this.msg = data.message;
});
this.sockets.unsubscribe('EVENT_NAME');
比如: