我正在使用webrtc,我想执行以下操作:
let connection = new WebSocket('ws://localhost:8080')
connection.onmessage = function (message) { // code }
因此,当我使用connection.send(//message)
时,应该触发.onmessage
事件。
但是我该如何在vue js中听呢?
这是我的vue代码的一部分:
data: {
connection: null
},
created: function() {
this.connection = new WebSocket('ws://localhost:8080')
// List cameras and microphones.
this.listDevices()
let app = this
this.connection.onmessage = function (message) {
console.log("Got message", message.data)
let data = JSON.parse(message.data)
switch(data.type) {
case "login":
app.onLogin(data.success)
break
case "offer":
app.onOffer(data.offer, data.name)
break
case "answer":
app.onAnswer(data.answer)
break
case "candidate":
app.onCandidate(data.candidate)
break
default:
break
}
}
this.connection.onopen = function() {
app.send({
type: "login",
name: 'myUsername'
})
}
},
methods: {
send: function(message) {
this.connection.send(JSON.stringify(message))
}
}
如您所见,我尝试使用created
的vue方法,但这种方法不起作用。那么,如何监听此.onmessage
事件并在其中调用我的vue应用程序中定义的其他方法?