这是我的代码无效:
connectSocket: function () {
this.socket = new WebSocket('ws://144.0.0.0:8080'); //IP Changed
this.socket.onopen = function(event) {
console.log("Connected to the Web Socket Server");
this.socket.send("Opponent has joined.");
};
alert("You're now connected to the server. Be careful out there.");
this.socket.onmessage = function(event) {
console.log("Message Received From Server :", event);
//This is the time to interact with this specific
};
}
我引用的代码是我的vue中的一个方法,称为身份验证。我只是尝试向Web套接字服务器发送和接收基本数据。然而,某处存在缺陷......如何解决这个问题并保持身份验证?
答案 0 :(得分:1)
您的事件处理程序在声明时会丢失上下文(this
)。使用箭头函数来保留当前上下文,因此this
引用Vue实例:
connectSocket: function () {
this.socket = new WebSocket('ws://144.0.0.0:8080'); //IP Changed
this.socket.onopen = (event) => { // changed to arrow function
console.log("Connected to the Web Socket Server");
this.socket.send("Opponent has joined.");
alert("You're now connected to the server. Be careful out there.");
};
this.socket.onmessage = (event) => { // changed to arrow function
console.log("Message Received From Server :", event);
//This is the time to interact with this specific
};
}
此外,你似乎有不平衡的花括号,所以我也改变了它们。但重要的是使用箭头功能。