我正在挂载中设置回调:
data() {
return {
code: 'Apple',
}
},
mounted() {
console.log(this.code) // prints 'Apple'
this.$options.sockets.onopen = this.wsOpen();
this.$options.sockets.onmessage = this.logMessage(msg);
},
methods: {
logMessage(msg){
this.code += "\n" + msg.data;
console.log("this.code: " + this.code);
},
}
但是它告诉我“msg”未定义。 以下内容有效,但是 this.code 超出了范围:
this.$options.sockets.onmessage= function (msg) {
console.log(msg.data) // this works, msg is not undefined here
console.log(this.code) // doesnt work, this.code is undefined
}
我觉得我在做一些愚蠢的事情。
最佳答案
只需将其设置为函数即可。
this.$options.sockets.onmessage = this.logMessage;
代码当前将 onmessage
设置为 this.logMessage(msg)
的结果,并且如错误所述, msg
未定义已安装
。
关于javascript - Websocket onmessage 事件不更新组件数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45467450/