2017-08-02 56 views
0

我设置在安装我的回调:的WebSocket的onMessage事件犯规更新组件数据

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); 
    }, 
} 

但是它告诉我,“味精”没有定义。 下面的作品,但是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

只需将其设置为该功能即可。

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

代码当前设置onmessage结果的this.logMessage(msg),并且作为错误状态,msg没有定义mounted