gpt4 book ai didi

javascript - Websocket onmessage 事件不更新组件数据

转载 作者:行者123 更新时间:2023-12-03 03:44:26 25 4
gpt4 key购买 nike

我正在挂载中设置回调:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com