src/utils新建socket.js
import {io} from "socket.io-client"
class Socket{
constructor(){
this.socket = io("http://127.0.0.1:5000");
}
// 连接socket
connect(){
this.socket.connect()
}
login(username,callback){
// emit发送
this.socket.emit('login',{"username":username},(result)=>{
if(callback){
callback(result);
}
})
}
// 是否连接socket
get connected(){
return this.socket.connected;
}
}
export default new Socket();
main
Login
methods: {
onSubmit() {
if(!this.form.username){
ElMessage.error("请输入用户名!")
return
}
// 判断socket是否登录
if(!this.$socket.connected){
this.$socket.connect();
}
this.$socket.login(this.form.username,(result)=>{
console.log(result)
});
}
}