小白终成大白
工作笔记
前言
vue 使用websocket 和后端进行长连接
一、场景
在vue2项目中生成一个二维码
扫码在手机操作 如何获取手机扫码的结果?
二、使用步骤
1.安装 amap/amap-jsapi-loader
代码如下(示例):
websocketInit(id) {//指定一个id 判断是哪个用户在进行连接
this.websocket = new WebSocket(`ws://qh6uaq.natappfree.cc/ssi-auth/pay?id=${id}`)
// ws://qh6uaq.natappfree.cc/ssi-auth/pay?id=${id} 这个是后端的连接地址
// 监听WebSocket事件
this.websocket.onopen = () => {
this.connectionStatus = 'connected'
console.log('connected') //连接成功
}
this.websocket.onclose = () => {
this.connectionStatus = 'disconnected'
}
this.websocket.onerror = () => {
this.connectionStatus = 'error'
}
//主要用这个onmessage 监听后端发送的消息
this.websocket.onmessage = event => {
console.log(event)
const message = JSON.parse(event.data)
this.receivedMessages.push(message)
console.log(message)//后端返回的消息
}
},
beforeDestroy() {
// 在组件销毁前关闭WebSocket连接
if (this.websocket) {
this.websocket.close()
}
}
}
备注
注意使用WebSocket完毕后关闭连接