【问题标题】:WebSockets won't Send data from Vue app - error states 'send' is undefined, Stack: Vue Express Mongo WebSocketsWebSockets 不会从 Vue 应用程序发送数据 - 错误状态“发送”未定义,堆栈:Vue Express Mongo WebSockets
【发布时间】:2018-04-21 03:28:22
【问题描述】:

这是我的代码不起作用:

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 Socket 服务器发送和接收基本数据。然而,这是有缺陷的地方......我该如何解决这个问题并保持身份验证?

【问题讨论】:

    标签: mongodb express vue.js websocket undefined


    【解决方案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
      };
    }
    

    而且你的大括号似乎不平衡,所以我也改变了它们。但重要的部分确实是箭头函数的使用。

    【讨论】:

    • 谢谢!这正是我需要的,我不太明白,但在这里查了developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。 => 是否有效,因为它没有自己的“this”,而如果我创建一个新函数,该函数有自己的“this”与之关联,所以父“this”不起作用?
    猜你喜欢
    • 2020-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 2020-09-28
    • 2016-02-21
    • 1970-01-01
    • 2020-03-29
    相关资源
    最近更新 更多