【发布时间】: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