在vue 创建了一个js 带如下
export class webSock {
constructor({url, open, error, onmessage, send, onclose}) {
this.url = url
open && (this.websocketOnOpen = open)
error && (this.websocketOnError = error)
onmessage && (this.websocketOnMessage = onmessage)
send && (this.websocketSend = send)
onclose && (this.websocketClose = onclose)
this.disconnection_reconnection=true
}
// 初始化websocket
initWebSocket() {
this.websock = new WebSocket(this.url)
this.websock.onmessage = this.websocketOnMessage
this.websock.onopen = this.websocketOnOpen
this.websock.onerror = this.websocketOnError
this.websock.onclose = this.websocketClose
}
// 连接建立成功的信号
websocketOnOpen(e) {
if (this.disconnection_reconnection) {
this.disconnection_reconnection = false
this.websocketSend({state: true})
} else {
this.websocketSend({state: false})
}
}
// 连接建立失败重连
websocketOnError() {
// 如果报错的话,在这里就可以重新初始化websocket,这就是断线重连
this.disconnection_reconnection=true
setTimeout(() => {
this.initWebSocket()
}, 1000)
}
// 数据接收
websocketOnMessage(e) {
console.log('接收内容:', e.data)
}
// 数据发送
websocketSend(Data) {
let data = JSON.stringify(Data)
this.websock.send(data)// Data变量就是你想对后台说些啥,根据后端给你的接口文档传值进行交互
}
// 关闭的信号
websocketClose() {
console.log('断开连接')
}
// 传参给后端,这里对websocketSend又进行了一层封装,用不到的可以删除
sendDevName(chooseDevice) {
this.websocketSend(chooseDevice)
}
}
在vue组件中调用方式如下
this.mywebsocket = new webSock(
{
//测试访问url
url: 'ws://42.193.48.210:8080/healthy/wbapi/pushMessage/104',
//数据接收处理函数
onmessage: this.websocketHandle,
})
this.mywebsocket.initWebSocket()
访问后websocketOnOpen 函数报错,说找不到websocketSend,disconnection_reconnection打印出来也是undefined
该如何解决这种问题
基于Monster 组和GPT的调写:
这个问题的原因是在你调用 this.websocketOnOpen 函数时, this 的上下文并不是 webSock 实例对象,而是 WebSocket 实例对象。因此,在 this.websocketOnOpen 函数中, this 指向的不是你创建的 webSock 对象,而是 WebSocket 对象,所以在 websocketOnOpen 函数中无法访问 webSock 对象的属性和方法,导致 websocketSend 和 disconnection_reconnection 属性都是 undefined。
要解决这个问题,一种方法是使用箭头函数来定义 websocketOnOpen 函数,这样可以确保在该函数内部, this 始终指向 webSock 实例对象。另一种方法是使用 bind 方法,将 this 绑定到 webSock 实例对象上。
下面是使用箭头函数的示例代码:
websocketOnOpen = (e) => {
if (this.disconnection_reconnection) {
this.disconnection_reconnection = false
this.websocketSend({state: true})
} else {
this.websocketSend({state: false})
}
}
另一种方法是使用 bind 方法:
constructor({url, open, error, onmessage, send, onclose}) {
// ...
this.websocketOnOpen = this.websocketOnOpen.bind(this)
// ...
}
这两种方法都可以解决上述问题。