2017-08-02 55 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