在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
该如何解决这种问题