Vue.js 在 websocket onmessage 事件中更新 html

时间:2021-05-03 21:27:00

标签: javascript html vue.js

我是 Vue.js 新手。我试图在 websocket 的 onmessage 事件中捕获数据并更新 HTML 组件(span 或 div)。 console.log 或警报功能在 onmessage 中工作,但无法更新跨度。

开头有一个模板部分,其中包含一个输入框(消息),一个按钮触发发送消息,以及一个与结果绑定的范围。

<template>
  <div id="app">
    <h2>Vue.js WebSocket</h2> 
    <input v-model="message" placeholder="Type command here"/>
    <button v-on:click="sendMessage()">Send Message</button><br><br>
    <span v-text="result"></span>
  </div>
</template>

这里是脚本部分;

<script>
export default {
  name: 'App',
  
  data: function () {
    return {
      connection:null,
      message:"",
      result:null
    }
  },

  methods: {
    sendMessage: function() {
      console.log("Sent command:" + this.message);
      console.log(this.connection);
      this.connection.send(this.message);
    },
  },

  created: function() {
    console.log("Starting connection to WebSocket Server");
    this.connection = new WebSocket("ws://localhost:3000");
    
    //THAT WORKS
    this.result = "Result of command";

    this.connection.onmessage = function(event) {
      console.log(event);
    }
    this.connection.onopen = function(event) {
      console.log(event);
      console.log("Successfully connected to the echo websocket server...")
    }
    this.connection.onmessage = function(event) {
      //THAT WORKS
      console.log("Resultttt:" + event.data);
      
      //THAT DOESN'T WORK
      this.result = event.data;
    }
    this.connection.onopen = function(event) {
      console.log(event);
      console.log("Successfully connected to the echo websocket server...");
    }
  }
}
</script>

1 个答案:

答案 0 :(得分:0)

这可能是上下文问题。尝试按如下所示进行更改,看看是否有效。

this.connection.onmessage = (event) => {
  // no new context ----------------^
  this.result = event.data;
}

const v = this;
this.connection.onmessage = function(event) {
  v.result = event.data;
}