【问题标题】:Vue.js updating html inside websocket onmessage eventVue.js 在 websocket onmessage 事件中更新 html
【发布时间】:2021-07-26 06:49:00
【问题描述】:

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

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

<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>

【问题讨论】:

  • 模板在哪里?究竟是什么不工作?请看minimal reproducible example
  • 添加了模板部分。 this.result = event.data 行在 this.connection.onmessage 中不起作用,但 event.data 不是未定义的。 console.log 打印它的值。

标签: javascript html vue.js


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 2022-11-13
    • 2015-02-28
    • 1970-01-01
    相关资源
    最近更新 更多