【问题标题】:Vue - unable to access component functions/data within handler methodVue - 无法在处理程序方法中访问组件功能/数据
【发布时间】:2020-10-29 16:54:28
【问题描述】:

我在 Vue 中有一个名为 doSomething() 的函数和一个名为 onmessage() 的事件处理程序,这也是它自己的函数。但是在 onmessage 中,我无法访问组件中的任何内容。我无法访问组件变量或方法。

如何从该函数中访问组件数据?

export default {
  name: "component",
  data() {
    return {
      name: "Jeb",
      connection: null
      }
  },
  methods: {
    doSomething: function() {
      
      this.connection = new WebSocket("ws://localhost:2000");
      this.connection.onmessage = function(event) {
       
         console.log(this.name); //UNDEFINED
         this.doAnotherThing(); //ERROR 
      };
      ...
      ...
    },
    doAnotherThing: function() {
      ...
    }
  }
};

如果之前有人问过这个问题,我提前道歉。我已经尝试搜索了一段时间,但找不到类似的帖子。

【问题讨论】:

  • 尝试使用箭头函数。如果你 console.log(this) 我假设它会记录 this.connection 变量,因为这是事件处理程序正在放置的内容

标签: javascript vue.js


【解决方案1】:

改变组织方法代码的方式:

doSomething() {
  this.connection = new WebSocket("ws://localhost:2000");
  ...

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 2019-11-05
    • 1970-01-01
    • 2019-12-11
    相关资源
    最近更新 更多