我在挂载中设置回调:
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
}
我认为我做的事情是愚蠢的。
答案 0 :(得分:1)
只需将其设置为该功能。
this.$options.sockets.onmessage = this.logMessage;
代码目前正将onmessage
设置为this.logMessage(msg)
的结果,并且由于错误状态,msg
未定义mounted
。