Websocket onmessage事件不会更新组件数据

时间:2017-08-02 17:32:05

标签: javascript callback event-handling vue.js

我在挂载中设置回调:

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
    }

我认为我做的事情是愚蠢的。

1 个答案:

答案 0 :(得分:1)

只需将其设置为该功能。

this.$options.sockets.onmessage = this.logMessage;

代码目前正将onmessage设置为this.logMessage(msg)结果,并且由于错误状态,msg未定义mounted